From c59c139444477fda75df8541cd8c7bcb5c93ec5b Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Sun, 22 May 2016 13:16:47 +0200 Subject: [PATCH 001/844] Implemented Amplitude SDK type definition. --- amplitude/amplitude-tests.ts | 85 ++++++++++++++++++++++++++++++++++++ amplitude/amplitude.d.ts | 58 ++++++++++++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 amplitude/amplitude-tests.ts create mode 100644 amplitude/amplitude.d.ts diff --git a/amplitude/amplitude-tests.ts b/amplitude/amplitude-tests.ts new file mode 100644 index 0000000000..c4ffb9e811 --- /dev/null +++ b/amplitude/amplitude-tests.ts @@ -0,0 +1,85 @@ +/// + +module Amplitude.Tests { + function all() { + amplitude.init('YOUR_API_KEY_HERE', null, { + // optional configuration options + saveEvents: true, + includeUtm: true, + includeReferrer: true, + batchEvents: true, + eventUploadThreshold: 50 + }); + amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE', null, () => {}); + + amplitude.logEvent('EVENT_IDENTIFIER_HERE'); + amplitude.setUserId('USER_ID_HERE'); + amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE'); + amplitude.setUserId(null); // not string 'null' + amplitude.setVersionName('VERSION_NAME_HERE'); + + amplitude.regenerateDeviceId(); + amplitude.setDeviceId('CUSTOM_DEVICE_ID'); + + amplitude.logEvent('EVENT_IDENTIFIER_HERE', { + 'color': 'blue', + 'age': 20, + 'key': 'value' + }); + amplitude.logEvent("EVENT_IDENTIFIER_HERE", null, (httpCode, response) => { }); + + let identify = new amplitude.Identify().set('gender', 'female').set('age', 20); + amplitude.identify(identify); + + identify = new amplitude.Identify().setOnce('sign_up_date', '08/24/2015'); + amplitude.identify(identify); + + identify = new amplitude.Identify().setOnce('sign_up_date', '09/14/2015'); + amplitude.identify(identify); + + identify = new amplitude.Identify().unset('gender').unset('age'); + amplitude.identify(identify); + + identify = new amplitude.Identify().add('karma', 1).add('friends', 1); + amplitude.identify(identify); + + identify = new amplitude.Identify().append('ab-tests', 'new-user-test').append('some_list', [1, 2, 3, 4, 'values']); + amplitude.identify(identify); + + identify = new amplitude.Identify().prepend('ab-tests', 'new-user-test').prepend('some_list', [1, 2, 3, 4, 'values']); + amplitude.identify(identify); + + identify = new amplitude.Identify() + .set('karma', 10) + .add('karma', 1) + .unset('karma'); + amplitude.identify(identify); + + identify = new amplitude.Identify() + .set('colors', ['rose', 'gold']) + .append('ab-tests', 'campaign_a') + .append('existing_list', [4, 5]); + amplitude.identify(identify); + + amplitude.setUserProperties({ + gender: 'female', + age: 20 + }); + + amplitude.clearUserProperties(); + + amplitude.setOptOut(true); + amplitude.setOptOut(false); + + amplitude.setGroup('orgId', '15'); + amplitude.setGroup('sport', ['soccer', 'tennis']); + + // Still to implement: + /* + var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3); + amplitude.logRevenueV2(revenue); + + amplitude.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' }); + */ + } +} diff --git a/amplitude/amplitude.d.ts b/amplitude/amplitude.d.ts new file mode 100644 index 0000000000..339153634d --- /dev/null +++ b/amplitude/amplitude.d.ts @@ -0,0 +1,58 @@ +declare module amplitude { + interface Config { + batchEvents?: boolean; + cookieExpiration?: number; + cookieName?: string; + deviceId?: string; + domain?: string; + eventUploadPeriodMillis?: number; + eventUploadThreshold?: number; + includeReferrer?: boolean; + includeUtm?: boolean; + language?: string; + optOut?: boolean; + platform?: string; + saveEvents?: boolean; + savedMaxCount?: number; + sessionTimeout?: number; + uploadBatchSize?: number; + } + + export class Identify { + set(key: string, value: any): Identify; + setOnce(key: string, value: any): Identify; + add(key: string, value: number): Identify; + append(key: string, value: any): Identify; + prepend(key: string, value: any): Identify; + + unset(key: string): Identify; + } + + export function init(apiKey: string): void; + export function init(apiKey: string, userId: string): void; + export function init(apiKey: string, userId: string, options: Config): void; + export function init(apiKey: string, userId: string, options: Config, callback: () => void): void; + + export function setVersionName(version: string): void; + export function setUserId(userId: string): void; + + export function setDeviceId(id: string): void; + export function regenerateDeviceId(): void; + + export function identify(identify: Identify): void; + + export function setUserProperties(properties: Object): void; + export function clearUserProperties(): void; + + export function setOptOut(optOut: boolean): void; + + export function setGroup(groupType: string, groupName: string | string[]); + + export function logEvent(event: string): void; + export function logEvent(event: string, data: Object): void; + export function logEvent(event: string, data: Object, callback: (httpCode: number, response: any) => void): void; + + export var options: Config; +} + +//declare var amplitude: AmplitudeStatic; From 9a055b462ad6465f999facbd3b7013e564bebfc2 Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Sun, 22 May 2016 13:37:31 +0200 Subject: [PATCH 002/844] Added required header comments to amplitude definition files. --- amplitude/amplitude-tests.ts | 2 ++ amplitude/amplitude.d.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/amplitude/amplitude-tests.ts b/amplitude/amplitude-tests.ts index c4ffb9e811..d60cf4bc7b 100644 --- a/amplitude/amplitude-tests.ts +++ b/amplitude/amplitude-tests.ts @@ -1,3 +1,5 @@ +// Tests for Amplitude SDK TypeScript definitions + /// module Amplitude.Tests { diff --git a/amplitude/amplitude.d.ts b/amplitude/amplitude.d.ts index 339153634d..3955ae128a 100644 --- a/amplitude/amplitude.d.ts +++ b/amplitude/amplitude.d.ts @@ -1,3 +1,5 @@ +// Type definitions for Amplitude SDK 2.12.1 + declare module amplitude { interface Config { batchEvents?: boolean; From ed54ec0de6b1ef627fcfd9382ae1e91c9aa97180 Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Sun, 22 May 2016 13:38:02 +0200 Subject: [PATCH 003/844] amplitude.setGroup() return value is now void instead instead of implicit any. --- amplitude/amplitude.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/amplitude/amplitude.d.ts b/amplitude/amplitude.d.ts index 3955ae128a..d3ad99c890 100644 --- a/amplitude/amplitude.d.ts +++ b/amplitude/amplitude.d.ts @@ -48,7 +48,7 @@ declare module amplitude { export function setOptOut(optOut: boolean): void; - export function setGroup(groupType: string, groupName: string | string[]); + export function setGroup(groupType: string, groupName: string | string[]): void; export function logEvent(event: string): void; export function logEvent(event: string, data: Object): void; From 6b5953e8d06043c69d3be715cef78ba278827503 Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Sun, 22 May 2016 13:40:29 +0200 Subject: [PATCH 004/844] Added required 'Project' comment to amplitude definition file header. --- amplitude/amplitude.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/amplitude/amplitude.d.ts b/amplitude/amplitude.d.ts index d3ad99c890..b8b208bcdd 100644 --- a/amplitude/amplitude.d.ts +++ b/amplitude/amplitude.d.ts @@ -1,4 +1,5 @@ // Type definitions for Amplitude SDK 2.12.1 +// Project: https://github.com/amplitude/Amplitude-Javascript declare module amplitude { interface Config { From 233b6e31fe562202a1c08a3eb23635350ab672fe Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Sun, 22 May 2016 13:43:33 +0200 Subject: [PATCH 005/844] Added required 'Definitions by' comment to amplitude definition file header. --- amplitude/amplitude.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/amplitude/amplitude.d.ts b/amplitude/amplitude.d.ts index b8b208bcdd..0e2c392e64 100644 --- a/amplitude/amplitude.d.ts +++ b/amplitude/amplitude.d.ts @@ -1,5 +1,6 @@ // Type definitions for Amplitude SDK 2.12.1 // Project: https://github.com/amplitude/Amplitude-Javascript +// Definitions by: Arvydas Sidorenko declare module amplitude { interface Config { From 759ae4713b69d6b96825c839472c0bf6c79662aa Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Sun, 22 May 2016 13:48:53 +0200 Subject: [PATCH 006/844] Added required 'Definitions' comment to amplitude definition file header. --- amplitude/amplitude.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/amplitude/amplitude.d.ts b/amplitude/amplitude.d.ts index 0e2c392e64..9a5df3d179 100644 --- a/amplitude/amplitude.d.ts +++ b/amplitude/amplitude.d.ts @@ -1,6 +1,7 @@ // Type definitions for Amplitude SDK 2.12.1 // Project: https://github.com/amplitude/Amplitude-Javascript // Definitions by: Arvydas Sidorenko +// Definitions: https://github.com/Asido/DefinitelyTyped declare module amplitude { interface Config { From beb9814807ffec927b1ef4eb74c735296ab33a63 Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Mon, 30 May 2016 10:11:37 +0200 Subject: [PATCH 007/844] Renamed amplitude to amplitude-js. --- .../amplitude-tests.ts => amplitude-js/amplitude-js-tests.ts | 4 ++-- amplitude/amplitude.d.ts => amplitude-js/amplitude-js.d.ts | 0 2 files changed, 2 insertions(+), 2 deletions(-) rename amplitude/amplitude-tests.ts => amplitude-js/amplitude-js-tests.ts (97%) rename amplitude/amplitude.d.ts => amplitude-js/amplitude-js.d.ts (100%) diff --git a/amplitude/amplitude-tests.ts b/amplitude-js/amplitude-js-tests.ts similarity index 97% rename from amplitude/amplitude-tests.ts rename to amplitude-js/amplitude-js-tests.ts index d60cf4bc7b..66285f10dd 100644 --- a/amplitude/amplitude-tests.ts +++ b/amplitude-js/amplitude-js-tests.ts @@ -1,6 +1,6 @@ // Tests for Amplitude SDK TypeScript definitions -/// +/// module Amplitude.Tests { function all() { @@ -76,7 +76,7 @@ module Amplitude.Tests { amplitude.setGroup('orgId', '15'); amplitude.setGroup('sport', ['soccer', 'tennis']); - // Still to implement: + // TODO: Implement those. /* var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3); amplitude.logRevenueV2(revenue); diff --git a/amplitude/amplitude.d.ts b/amplitude-js/amplitude-js.d.ts similarity index 100% rename from amplitude/amplitude.d.ts rename to amplitude-js/amplitude-js.d.ts From 679c3b36fe6ff78e323f0940b6e7c170acdfbc1b Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 08:48:05 -0400 Subject: [PATCH 008/844] Create masonry-layout-tests.ts --- masonry-layout/masonry-layout-tests.ts | 1 + 1 file changed, 1 insertion(+) create mode 100644 masonry-layout/masonry-layout-tests.ts diff --git a/masonry-layout/masonry-layout-tests.ts b/masonry-layout/masonry-layout-tests.ts new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/masonry-layout/masonry-layout-tests.ts @@ -0,0 +1 @@ + From 8b6b2cad03bc33b0b3b5018c5adbdc802f0b17c6 Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 09:21:19 -0400 Subject: [PATCH 009/844] Delete masonry-layout-tests.ts --- masonry-layout/masonry-layout-tests.ts | 1 - 1 file changed, 1 deletion(-) delete mode 100644 masonry-layout/masonry-layout-tests.ts diff --git a/masonry-layout/masonry-layout-tests.ts b/masonry-layout/masonry-layout-tests.ts deleted file mode 100644 index 8b13789179..0000000000 --- a/masonry-layout/masonry-layout-tests.ts +++ /dev/null @@ -1 +0,0 @@ - From f595e716b97bab9d3d8a22e4b81a5a989cd913a6 Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 09:22:32 -0400 Subject: [PATCH 010/844] Add files via upload --- masonry-layout-tests.ts | 48 ++++++++++++++++++++++++++++ masonry-layout.d.ts | 70 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 118 insertions(+) create mode 100644 masonry-layout-tests.ts create mode 100644 masonry-layout.d.ts diff --git a/masonry-layout-tests.ts b/masonry-layout-tests.ts new file mode 100644 index 0000000000..e83a898f54 --- /dev/null +++ b/masonry-layout-tests.ts @@ -0,0 +1,48 @@ +// test file for masonry-layout.d.ts + +/// +/// + +//import {Masonry} from "./masonry-layout.d.ts"; + +// responsive layouts +function testResponsiveLayouts() { + $('.grid').masonry({ + itemSelector: '.grid-item', + columnWidth: '.grid-sizer', + percentPosition: true + }); +} + +// recommended Options +function testRecommendedOptions() { + $('.grid').masonry({ + columnWidth: 200, + itemSelector: '.grid-item' + }); + + var msnry = new Masonry.Masonry('.grid', { + columnWidth: 200, + itemSelector: '.grid-item' + }); +} + +// extended Options +function testExtendedOptions() { + var msnry = new Masonry.Masonry('.grid', { + itemSelector: '.grid-item', + columnWidth: '.grid-sizer', + percentPosition: true, + gutter: '.gutter-sizer', + stamp: '.stamp', + fitWidth: true, + originLeft: true, + originTop: true, + containerStyle: { + position: 'relative' + }, + transitionDuration: '0.4s', + resize: true, + initLayout: true + }); +} diff --git a/masonry-layout.d.ts b/masonry-layout.d.ts new file mode 100644 index 0000000000..0923a8f463 --- /dev/null +++ b/masonry-layout.d.ts @@ -0,0 +1,70 @@ +// Type definitions for Masonry 4.0.0 +// Project: https://github.com/desandro/masonry +// Definitions by: Mark Wilson +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +// Modified from original definitions by: +// Travis Brown < https://github.com/warriorrocker> + +declare module Masonry { + + class Masonry implements MasonryGrid { + constructor(options?: MasonryOptions); + constructor(selector: string, options?: MasonryOptions); + } + + interface MasonryGrid { + masonry?(): void; + masonry?(eventName: string, listener: any): void; + + // layout + layout?(): void; + layoutItems?(items: Array, isStill?: boolean): void; + stamp?(elements: Array): void; + unstamp?(elements: Array): void; + + // add and remove items + appended?(elements: Array): void; + prepended?(elements: Array): void; + addItems?(elements: Array): void; + remove?(elements: Array): void; + + // events + on?(eventName: string, listener: any): void; + off?(eventName: string, listener: any): void; + once?(eventName: string, listener: any): void; + + // utilities + reloadItems?(): void; + destroy?(): void; + getItemElements?(): Array; + data?(element: Element): Masonry; + } + + interface MasonryOptions { + + // layout + itemSelector?: string; + columnWidth?: any; + percentPosition?: boolean; + gutter?: any; + stamp?: string; + fitWidth?: boolean; + originLeft?: boolean; + originTop?: boolean; + + // setup + containerStyle?: Object; + transitionDuration?: any; + resize?: boolean; + initLayout?: boolean; + } +} + +interface JQuery { + masonry(options?: Masonry.MasonryOptions): JQuery; +} + + From c8b868b4f4dbeb4459effd91ea29aad21f83f860 Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 09:23:49 -0400 Subject: [PATCH 011/844] Delete masonry-layout.d.ts --- masonry-layout.d.ts | 70 --------------------------------------------- 1 file changed, 70 deletions(-) delete mode 100644 masonry-layout.d.ts diff --git a/masonry-layout.d.ts b/masonry-layout.d.ts deleted file mode 100644 index 0923a8f463..0000000000 --- a/masonry-layout.d.ts +++ /dev/null @@ -1,70 +0,0 @@ -// Type definitions for Masonry 4.0.0 -// Project: https://github.com/desandro/masonry -// Definitions by: Mark Wilson -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -// Modified from original definitions by: -// Travis Brown < https://github.com/warriorrocker> - -declare module Masonry { - - class Masonry implements MasonryGrid { - constructor(options?: MasonryOptions); - constructor(selector: string, options?: MasonryOptions); - } - - interface MasonryGrid { - masonry?(): void; - masonry?(eventName: string, listener: any): void; - - // layout - layout?(): void; - layoutItems?(items: Array, isStill?: boolean): void; - stamp?(elements: Array): void; - unstamp?(elements: Array): void; - - // add and remove items - appended?(elements: Array): void; - prepended?(elements: Array): void; - addItems?(elements: Array): void; - remove?(elements: Array): void; - - // events - on?(eventName: string, listener: any): void; - off?(eventName: string, listener: any): void; - once?(eventName: string, listener: any): void; - - // utilities - reloadItems?(): void; - destroy?(): void; - getItemElements?(): Array; - data?(element: Element): Masonry; - } - - interface MasonryOptions { - - // layout - itemSelector?: string; - columnWidth?: any; - percentPosition?: boolean; - gutter?: any; - stamp?: string; - fitWidth?: boolean; - originLeft?: boolean; - originTop?: boolean; - - // setup - containerStyle?: Object; - transitionDuration?: any; - resize?: boolean; - initLayout?: boolean; - } -} - -interface JQuery { - masonry(options?: Masonry.MasonryOptions): JQuery; -} - - From 1b6467c9f19e2ed180b92c1ac430311d1e557a29 Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 09:25:31 -0400 Subject: [PATCH 012/844] Delete masonry-layout-tests.ts --- masonry-layout-tests.ts | 48 ----------------------------------------- 1 file changed, 48 deletions(-) delete mode 100644 masonry-layout-tests.ts diff --git a/masonry-layout-tests.ts b/masonry-layout-tests.ts deleted file mode 100644 index e83a898f54..0000000000 --- a/masonry-layout-tests.ts +++ /dev/null @@ -1,48 +0,0 @@ -// test file for masonry-layout.d.ts - -/// -/// - -//import {Masonry} from "./masonry-layout.d.ts"; - -// responsive layouts -function testResponsiveLayouts() { - $('.grid').masonry({ - itemSelector: '.grid-item', - columnWidth: '.grid-sizer', - percentPosition: true - }); -} - -// recommended Options -function testRecommendedOptions() { - $('.grid').masonry({ - columnWidth: 200, - itemSelector: '.grid-item' - }); - - var msnry = new Masonry.Masonry('.grid', { - columnWidth: 200, - itemSelector: '.grid-item' - }); -} - -// extended Options -function testExtendedOptions() { - var msnry = new Masonry.Masonry('.grid', { - itemSelector: '.grid-item', - columnWidth: '.grid-sizer', - percentPosition: true, - gutter: '.gutter-sizer', - stamp: '.stamp', - fitWidth: true, - originLeft: true, - originTop: true, - containerStyle: { - position: 'relative' - }, - transitionDuration: '0.4s', - resize: true, - initLayout: true - }); -} From 4a63acbbde3f494510e7bafea9d143a4f6caa907 Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 09:44:05 -0400 Subject: [PATCH 013/844] Create masonry-layout-tests.ts --- masonry-layout/masonry-layout-tests.ts | 1 + 1 file changed, 1 insertion(+) create mode 100644 masonry-layout/masonry-layout-tests.ts diff --git a/masonry-layout/masonry-layout-tests.ts b/masonry-layout/masonry-layout-tests.ts new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/masonry-layout/masonry-layout-tests.ts @@ -0,0 +1 @@ + From 8c3dd98cd712050a5a50c232b074ba74758de453 Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 09:44:37 -0400 Subject: [PATCH 014/844] Add files via upload --- masonry-layout/masonry-layout-tests.ts | 49 +++++++++++++++++- masonry-layout/masonry-layout.d.ts | 70 ++++++++++++++++++++++++++ 2 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 masonry-layout/masonry-layout.d.ts diff --git a/masonry-layout/masonry-layout-tests.ts b/masonry-layout/masonry-layout-tests.ts index 8b13789179..e83a898f54 100644 --- a/masonry-layout/masonry-layout-tests.ts +++ b/masonry-layout/masonry-layout-tests.ts @@ -1 +1,48 @@ - +// test file for masonry-layout.d.ts + +/// +/// + +//import {Masonry} from "./masonry-layout.d.ts"; + +// responsive layouts +function testResponsiveLayouts() { + $('.grid').masonry({ + itemSelector: '.grid-item', + columnWidth: '.grid-sizer', + percentPosition: true + }); +} + +// recommended Options +function testRecommendedOptions() { + $('.grid').masonry({ + columnWidth: 200, + itemSelector: '.grid-item' + }); + + var msnry = new Masonry.Masonry('.grid', { + columnWidth: 200, + itemSelector: '.grid-item' + }); +} + +// extended Options +function testExtendedOptions() { + var msnry = new Masonry.Masonry('.grid', { + itemSelector: '.grid-item', + columnWidth: '.grid-sizer', + percentPosition: true, + gutter: '.gutter-sizer', + stamp: '.stamp', + fitWidth: true, + originLeft: true, + originTop: true, + containerStyle: { + position: 'relative' + }, + transitionDuration: '0.4s', + resize: true, + initLayout: true + }); +} diff --git a/masonry-layout/masonry-layout.d.ts b/masonry-layout/masonry-layout.d.ts new file mode 100644 index 0000000000..0923a8f463 --- /dev/null +++ b/masonry-layout/masonry-layout.d.ts @@ -0,0 +1,70 @@ +// Type definitions for Masonry 4.0.0 +// Project: https://github.com/desandro/masonry +// Definitions by: Mark Wilson +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +// Modified from original definitions by: +// Travis Brown < https://github.com/warriorrocker> + +declare module Masonry { + + class Masonry implements MasonryGrid { + constructor(options?: MasonryOptions); + constructor(selector: string, options?: MasonryOptions); + } + + interface MasonryGrid { + masonry?(): void; + masonry?(eventName: string, listener: any): void; + + // layout + layout?(): void; + layoutItems?(items: Array, isStill?: boolean): void; + stamp?(elements: Array): void; + unstamp?(elements: Array): void; + + // add and remove items + appended?(elements: Array): void; + prepended?(elements: Array): void; + addItems?(elements: Array): void; + remove?(elements: Array): void; + + // events + on?(eventName: string, listener: any): void; + off?(eventName: string, listener: any): void; + once?(eventName: string, listener: any): void; + + // utilities + reloadItems?(): void; + destroy?(): void; + getItemElements?(): Array; + data?(element: Element): Masonry; + } + + interface MasonryOptions { + + // layout + itemSelector?: string; + columnWidth?: any; + percentPosition?: boolean; + gutter?: any; + stamp?: string; + fitWidth?: boolean; + originLeft?: boolean; + originTop?: boolean; + + // setup + containerStyle?: Object; + transitionDuration?: any; + resize?: boolean; + initLayout?: boolean; + } +} + +interface JQuery { + masonry(options?: Masonry.MasonryOptions): JQuery; +} + + From 5f755e7938ad3da1ce7705c3b640f575e3e34f34 Mon Sep 17 00:00:00 2001 From: Gabriel JUCHAULT Date: Thu, 21 Jul 2016 15:22:00 +0200 Subject: [PATCH 015/844] Countdown.js --- countdown/countdown-tests.ts | 47 ++++++++++++++++++++++++ countdown/countdown.d.ts | 69 ++++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 countdown/countdown-tests.ts create mode 100644 countdown/countdown.d.ts diff --git a/countdown/countdown-tests.ts b/countdown/countdown-tests.ts new file mode 100644 index 0000000000..900d2d6652 --- /dev/null +++ b/countdown/countdown-tests.ts @@ -0,0 +1,47 @@ +// Type definitions for countdown.js +// Project: http://countdownjs.org/ +// Definitions by: Gabriel Juchault https://github.com/gjuchault +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { countdown, Timespan, CountdownStatic, Format } from 'countdown'; + +let ts: Timespan; +let interval: number; + +ts = countdown(new Date()); +ts = countdown(150); + +interval = countdown(new Date(), + function (ts: Timespan) { + document.getElementById('pageTimer').innerHTML = ts.toHTML('strong'); + }, + countdown.HOURS | countdown.MINUTES | countdown.SECONDS, + 2, + 2 +); + +clearInterval(interval); + +ts.toString('foo'); +ts.toHTML('em', 'foo'); + +countdown.resetFormat(); +countdown.setLabels('a', 'b', 'c', 'd', 'e'); + +countdown.setLabels('a', 'b', 'c', 'd', 'e', function (value: number): string { + return 'ok'; +}, function (value: number, unit: number): string { + return 'ok'; +}); + +countdown.setLabels(null, null, null, null, 'Now.'); + +countdown.setLabels( + ' millisecond| second| minute| hour| day| week| month| year| decade| century| millennium', + ' milliseconds| seconds| minutes| hours| days| weeks| months| years| decades| centuries| millennia', + ' and ', + ', ', + '', + n => n.toString()); diff --git a/countdown/countdown.d.ts b/countdown/countdown.d.ts new file mode 100644 index 0000000000..dd604a36f8 --- /dev/null +++ b/countdown/countdown.d.ts @@ -0,0 +1,69 @@ +// Type definitions for countdown.js +// Project: http://countdownjs.org/ +// Definitions by: Gabriel Juchault +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'countdown' { + export type DateFunction = (timespan: Timespan) => void; + export type DateTime = number | Date | DateFunction; + + export interface Timespan { + start?: Date; + end?: Date; + units?: number; + value?: number; + millennia?: number; + centuries?: number; + decades?: number; + years?: number; + months?: number; + days?: number; + hours?: number; + minutes?: number; + seconds?: number; + milliseconds?: number; + toString(label?: string): string; + toHTML(tagName?: string, label?: string): string; + } + + export interface Format { + singular?: string | Array; + plural?: string | Array; + last?: string; + delim?: string; + empty?: string; + formatNumber?(value: number): string; + formatter?(value: number, unit: number): string; + } + + export interface CountdownStatic { + (start: DateTime, end?: DateTime, units?: number, max?: number, digits?: number): Timespan | number; + MILLENNIA: number; + CENTURIES: number; + DECADES: number; + YEARS: number; + MONTHS: number; + WEEKS: number; + DAYS: number; + HOURS: number; + MINUTES: number; + SECONDS: number; + MILLISECONDS: number; + ALL: number; + DEFAULTS: number; + resetLabels(): void; + setLabels( + singular?: string, + plural?: string, + last?: string, + delim?: string, + empty?: string, + formatNumber?: (value: number) => string, + formatter?: (value: number, unit: number) => string + ): void; + resetFormat(): void; + setFormat(format: Format): void; + } + + export var countdown: CountdownStatic; +} From b140e9b8f238b277469930d82353b6c5316b09fd Mon Sep 17 00:00:00 2001 From: Gabriel JUCHAULT Date: Thu, 21 Jul 2016 15:25:12 +0200 Subject: [PATCH 016/844] Remove header tags from tests --- countdown/countdown-tests.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/countdown/countdown-tests.ts b/countdown/countdown-tests.ts index 900d2d6652..c803f1acc2 100644 --- a/countdown/countdown-tests.ts +++ b/countdown/countdown-tests.ts @@ -1,8 +1,3 @@ -// Type definitions for countdown.js -// Project: http://countdownjs.org/ -// Definitions by: Gabriel Juchault https://github.com/gjuchault -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - /// import { countdown, Timespan, CountdownStatic, Format } from 'countdown'; From 125a1e48c38c78c974bed09b04b82bbfb883b9ca Mon Sep 17 00:00:00 2001 From: Gabriel JUCHAULT Date: Fri, 22 Jul 2016 15:45:21 +0200 Subject: [PATCH 017/844] fix(countdownjs): removed var --- countdown/countdown.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/countdown/countdown.d.ts b/countdown/countdown.d.ts index dd604a36f8..5b40541dd0 100644 --- a/countdown/countdown.d.ts +++ b/countdown/countdown.d.ts @@ -65,5 +65,5 @@ declare module 'countdown' { setFormat(format: Format): void; } - export var countdown: CountdownStatic; + export let countdown: CountdownStatic; } From bc0ecd2c61698592e8754f7aeb7493f6b67c31f9 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Thu, 28 Jul 2016 11:08:36 +0900 Subject: [PATCH 018/844] Sleep --- sleep/sleep-tests.ts | 6 ++++++ sleep/sleep.d.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 sleep/sleep-tests.ts create mode 100644 sleep/sleep.d.ts diff --git a/sleep/sleep-tests.ts b/sleep/sleep-tests.ts new file mode 100644 index 0000000000..2d2c05c2ff --- /dev/null +++ b/sleep/sleep-tests.ts @@ -0,0 +1,6 @@ +/// + +import sleep = require("sleep"); + +sleep.sleep(1); +sleep.usleep(5000); \ No newline at end of file diff --git a/sleep/sleep.d.ts b/sleep/sleep.d.ts new file mode 100644 index 0000000000..5173e4b4ef --- /dev/null +++ b/sleep/sleep.d.ts @@ -0,0 +1,26 @@ +// Type definitions for node-scanf +// Project: https://github.com/ErikDubbelboer/node-sleep +// Definitions by: Jeongho Nam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace __node_sleep +{ + /** + * Sleep for n seconds. + * + * @param n Number of seconds to sleep. + */ + function sleep(n: number): void; + + /** + * Sleep for n microseconds. + * + * @param n Number of microseconds to sleep; 1 second is 1,000,000 microseconds. + */ + function usleep(n: number): void; +} + +declare module "sleep" +{ + export = __node_sleep; +} \ No newline at end of file From 0bb3ec00dd31d85a43695aca33b72ff69c444ee5 Mon Sep 17 00:00:00 2001 From: Diullei Date: Fri, 8 Jul 2016 00:44:30 -0300 Subject: [PATCH 019/844] improved - blessedjs typings --- blessed/blessed-tests.ts | 773 ++++++++ blessed/blessed.d.ts | 4059 ++++++++++++++++++++++++++------------ 2 files changed, 3585 insertions(+), 1247 deletions(-) create mode 100644 blessed/blessed-tests.ts diff --git a/blessed/blessed-tests.ts b/blessed/blessed-tests.ts new file mode 100644 index 0000000000..4e7f7002e6 --- /dev/null +++ b/blessed/blessed-tests.ts @@ -0,0 +1,773 @@ +/// + +import * as blessed from 'blessed'; + +let screen: blessed.Widgets.Screen = null; + +// https://github.com/chjj/blessed/blob/master/test/widget-autopad.js + +screen = blessed.screen({ + dump: __dirname + '/logs/autopad.log', + smartCSR: true, + autoPadding: true, + warnings: true +}); + +var box1 = blessed.box({ + parent: screen, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line' +}); + +var box2 = blessed.box({ + parent: box1, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line' +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-bigtext.js + +screen = blessed.screen({ + dump: __dirname + '/logs/bigtext.log', + smartCSR: true, + warnings: true +}); + +var box = blessed.bigtext({ + parent: screen, + content: 'Hello', + shrink: true, + width: '80%', + // height: '80%', + height: 'shrink', + // width: 'shrink', + border: 'line', + fch: ' ', + ch: '\u2592', + style: { + fg: 'red', + bg: 'blue', + bold: false + } +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-csr.js + +screen = blessed.screen({ + dump: __dirname + '/logs/csr.log', + smartCSR: true, + warnings: true +}); + +var lorem = require('fs').readFileSync(__dirname + '/git.diff', 'utf8'); + +var cleanSides = screen.cleanSides; +function expectClean(value: any) { + screen.cleanSides = function(el: blessed.widget.Element) { + var ret = cleanSides.apply(this, arguments); + if (ret !== value) { + throw new Error('Failed. Expected ' + + value + ' from cleanSides. Got ' + + ret + '.'); + } + return ret; + }; +} +var btext = blessed.box({ + parent: screen, + left: 'center', + top: 'center', + width: '80%', + height: '80%', + style: { + bg: 'green' + }, + border: 'line', + content: 'CSR should still work.' +}); +let _oscroll = btext.scroll; +btext.scroll = function(offset, always) { + expectClean(true); + return _oscroll(offset, always); +}; + +var text = blessed.scrollabletext({ + parent: screen, + content: lorem, + border: 'line', + left: 'center', + top: 'center', + draggable: true, + width: '50%', + height: '50%', + mouse: true, + keys: true, + vi: true +}); + +_oscroll = text.scroll; +text.scroll = function(offset, always) { + var el = this; + var value = true; + if (el.left < 0) value = true; + if (el.top < 0) value = false; + if (el.left + el.width > screen.width) value = true; + if (el.top + el.height > screen.height) value = false; + expectClean(value); + return _oscroll(offset, always); +}; + +text.focus(); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-dock-noborder.js + +screen = blessed.screen({ + dump: __dirname + '/logs/dock.log', + smartCSR: true, + dockBorders: true, + warnings: true +}); + +blessed.box({ + parent: screen, + left: -1, + top: -1, + width: '50%+1', + height: '50%+1', + border: 'line', + content: 'Foo' +}); + +blessed.box({ + parent: screen, + left: '50%-1', + top: -1, + width: '50%+3', + height: '50%+1', + content: 'Bar', + border: 'line' +}); + +blessed.box({ + parent: screen, + left: -1, + top: '50%-1', + width: '50%+1', + height: '50%+3', + border: 'line', + content: 'Foo' +}); + +blessed.listtable({ + parent: screen, + left: '50%-1', + top: '50%-1', + width: '50%+3', + height: '50%+3', + border: 'line', + align: 'center', + tags: true, + keys: true, + vi: true, + mouse: true, + style: { + header: { + fg: 'blue', + bold: true + }, + cell: { + fg: 'magenta', + selected: { + bg: 'blue' + } + } + }, + data: [ + [ 'Animals', 'Foods', 'Times', 'Numbers' ], + [ 'Elephant', 'Apple', '1:00am', 'One' ], + [ 'Bird', 'Orange', '2:15pm', 'Two' ], + [ 'T-Rex', 'Taco', '8:45am', 'Three' ], + [ 'Mouse', 'Cheese', '9:05am', 'Four' ] + ] +}).focus(); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://raw.githubusercontent.com/chjj/blessed/master/example/simple-form.js + +var form = blessed.form({ + parent: screen, + keys: true, + left: 0, + top: 0, + width: 30, + height: 4, + bg: 'green', + content: 'Submit or cancel?' +}); + +var submit = blessed.button({ + parent: form, + mouse: true, + keys: true, + padding: { + left: 1, + right: 1 + }, + left: 10, + top: 2, + shrink: true, + name: 'submit', + content: 'submit', + style: { + bg: 'blue', + focus: { + bg: 'red' + }, + hover: { + bg: 'red' + } + } +}); + +var cancel = blessed.button({ + parent: form, + mouse: true, + keys: true, + padding: { + left: 1, + right: 1 + }, + left: 20, + top: 2, + shrink: true, + name: 'cancel', + content: 'cancel', + style: { + bg: 'blue', + focus: { + bg: 'red' + }, + hover: { + bg: 'red' + } + } +}); + +// https://github.com/chjj/blessed/blob/master/test/widget-layout.js + +screen = blessed.screen({ + dump: __dirname + '/logs/layout.log', + smartCSR: true, + autoPadding: true, + warnings: true +}); + +var layout = blessed.layout({ + parent: screen, + top: 'center', + left: 'center', + width: '50%', + height: '50%', + border: 'line', + layout: process.argv[2] === 'grid' ? 'grid' : 'inline', + style: { + bg: 'red', + border: { + fg: 'blue' + } + } +}); + +var box1 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '1' +}); + +var box2 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '2' +}); + +var box3 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '3' +}); + +var box4 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '4' +}); + +var box5 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '5' +}); + +var box6 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '6' +}); + +var box7 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '7' +}); + +var box8 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '8' +}); + +var box9 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '9' +}); + +var box10 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '10' +}); + +var box11 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '11' +}); + +var box12 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '12' +}); + +if (process.argv[2] !== 'grid') { + for (var i = 0; i < 10; i++) { + blessed.box({ + parent: layout, + // width: i % 2 === 0 ? 10 : 20, + // height: i % 2 === 0 ? 5 : 10, + width: Math.random() > 0.5 ? 10 : 20, + height: Math.random() > 0.5 ? 5 : 10, + border: 'line', + content: (i + 1 + 12) + '' + }); + } +} + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-form.js + +screen = blessed.screen({ + dump: __dirname + '/logs/form.log', + warnings: true +}); + +type FormData = { + radio1: boolean; + radio2: boolean; + text: string; + check: boolean; +}; + +var form2 = blessed.form({ + parent: screen, + mouse: true, + keys: true, + vi: true, + left: 0, + top: 0, + width: '100%', + //height: 12, + style: { + bg: 'green', + border: { + inverse: true + }, + scrollbar: { + inverse: true + } + }, + content: 'foobar', + scrollable: true, + scrollbar: { + ch: ' ' + } + //alwaysScroll: true +}); + +form2.on('submit', (data) => { + output.setContent(JSON.stringify(data, null, 2)); + screen.render(); +}); + +form2.key('d', function() { + form2.scroll(1, true); + screen.render(); +}); + +form2.key('u', function() { + form2.scroll(-1, true); + screen.render(); +}); + +var set = blessed.radioset({ + parent: form2, + left: 1, + top: 1, + shrink: true, + //padding: 1, + //content: 'f', + style: { + bg: 'magenta' + } +}); + +var radio1 = blessed.radiobutton({ + parent: set, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 0, + top: 0, + name: 'radio1', + content: 'radio1' +}); + +var radio2 = blessed.radiobutton({ + parent: set, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 15, + top: 0, + name: 'radio2', + content: 'radio2' +}); + +var text2 = blessed.textbox({ + parent: form2, + mouse: true, + keys: true, + style: { + bg: 'blue' + }, + height: 1, + width: 20, + left: 1, + top: 3, + name: 'text' +}); + +text2.on('focus', function() { + text2.readInput(); +}); + +var check = blessed.checkbox({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 28, + top: 1, + name: 'check', + content: 'check' +}); + +var check2 = blessed.checkbox({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 28, + top: 14, + name: 'foooooooo2', + content: 'foooooooo2' +}); + +var submit = blessed.button({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + padding: { + left: 1, + right: 1 + }, + left: 29, + top: 3, + name: 'submit', + content: 'submit', + style: { + bg: 'blue', + focus: { + bg: 'red' + } + } +}); + +submit.on('press', function() { + form2.submit(); +}); + +var box1 = blessed.box({ + parent: form2, + left: 1, + top: 10, + height: 10, + width: 10, + content: 'one', + style: { + bg: 'cyan' + } +}); + +var box2 = blessed.box({ + parent: box1, + left: 1, + top: 2, + height: 8, + width: 9, + content: 'two', + style: { + bg: 'magenta' + } +}); + +var box3 = blessed.box({ + parent: box2, + left: 1, + top: 2, + height: 6, + width: 8, + content: 'three', + style: { + bg: 'yellow' + } +}); + +var box4 = blessed.box({ + parent: box3, + left: 1, + top: 2, + height: 4, + width: 7, + content: 'four', + style: { + bg: 'blue' + } +}); + +var output = blessed.scrollabletext({ + parent: form2, + mouse: true, + keys: true, + left: 0, + top: 20, + height: 5, + right: 0, + style: { + bg: 'red' + }, + content: 'foobar' +}); + +var bottom = blessed.line({ + parent: form2, + type: 'line', + orientation: 'horizontal', + left: 0, + right: 0, + top: 50, + style: { + fg: 'blue' + } +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +form2.focus(); + +form2.submit(); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-table.js + +screen = blessed.screen({ + dump: __dirname + '/logs/table.log', + autoPadding: false, + fullUnicode: true, + warnings: true +}); + +var DU = '杜'; +var JUAN = '鹃'; + +var table = blessed.table({ + //parent: screen, + top: 'center', + left: 'center', + data: null, + border: 'line', + align: 'center', + tags: true, + //width: '80%', + width: 'shrink', + style: { + border: { + fg: 'red' + }, + header: { + fg: 'blue', + bold: true + }, + cell: { + fg: 'magenta' + } + } +}); + +var data1 = [ + [ 'Animals', 'Foods', 'Times' ], + [ 'Elephant', 'Apple', '1:00am' ], + [ 'Bird', 'Orange', '2:15pm' ], + [ 'T-Rex', 'Taco', '8:45am' ], + [ 'Mouse', 'Cheese', '9:05am' ] +]; + +data1[1][0] = '{red-fg}' + data1[1][0] + '{/red-fg}'; +data1[2][0] += ' (' + DU + JUAN + ')'; + +var data2 = [ + [ 'Animals', 'Foods', 'Times', 'Numbers' ], + [ 'Elephant', 'Apple', '1:00am', 'One' ], + [ 'Bird', 'Orange', '2:15pm', 'Two' ], + [ 'T-Rex', 'Taco', '8:45am', 'Three' ], + [ 'Mouse', 'Cheese', '9:05am', 'Four' ] +]; + +data2[1][0] = '{red-fg}' + data2[1][0] + '{/red-fg}'; +data2[2][0] += ' (' + DU + JUAN + ')'; + +screen.key('q', function() { + return screen.destroy(); +}); + +table.setData(data2); +screen.append(table); +screen.render(); + +setTimeout(function() { + table.setData(data1); + screen.render(); +}, 3000); diff --git a/blessed/blessed.d.ts b/blessed/blessed.d.ts index 6746afe5f5..cb9bd393ed 100644 --- a/blessed/blessed.d.ts +++ b/blessed/blessed.d.ts @@ -1,1256 +1,155 @@ -// Type definitions for blessed 0.1.5 +// Type definitions for blessed 0.1.81 // Project: https://github.com/chjj/blessed -// Definitions by: bryn austin bellomy +// Definitions by: bryn austin bellomy , Diullei Gomes // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// -declare module "blessed" -{ - import events = require('events'); - import buffer = require('buffer'); - import child_process = require('child_process'); +declare module "blessed" { + import {EventEmitter} from 'events'; + import * as stream from "stream" + import * as child_process from "child_process"; - module Blessed - { - export var colors: Colors; + export class BlessedProgram { + hideCursor: () => void; + move: any; + showCursor: any; + } - export interface GenericCallback { - (...args:any[]): void; + export module Widgets { + + export module Types { + + export type TTopLeft = string | number | "center"; + + export type TPosition = string | number; + + export type TMouseAction = "mousedown" | "mouseup" | "mousemove"; + + export type TStyle = { + type?: string; + bg?: string; + fg?: string; + ch?: string; + bold?: boolean; + underline?: boolean; + blink?: boolean; + inverse?: boolean; + invisible?: boolean; + transparent?: boolean; + border?: "line" | "bg" | TBorder; + hover?: boolean; + focus?: boolean; + label?: string; + track?: {bg?: string; fg?: string;}; + scrollbar?: {bg?: string; fg?: string;}; + } + + export type TBorder = { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; + /** + * Character to use if bg type, default is space. + */ + ch?: string; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + /** + * Border attributes. + */ + bold?: string; + underline?: string; + } + + export type TCursor = { + /** + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; + /** + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: boolean; + /** + * Whether the cursor blinks. + */ + blink: boolean; + /** + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; + } + + export type TAlign = "left" | "center" | "right"; + + export type ListbarCommand = { + key: string; + callback: () => void; + }; + + export type TImage = { + /** + * Pixel width. + */ + width: number; + /** + * Pixel height. + */ + height: number; + /** + * Image bitmap. + * */ + bmp: any; + /** + * Image cellmap (bitmap scaled down to cell size). + */ + cellmap: any; + }; + + export type Cursor = { + /** + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; + /** + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: boolean; + /** + * Whether the cursor blinks. + */ + blink: boolean; + /** + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; + } } - export interface ColorPair { - /** background, must be number (-1 for default). */ - bg?: number; - /** foreground, must be number (-1 for default). */ - fg?: number; - } - - export interface Style extends ColorPair { - bold?: boolean; - underline?: boolean; - border: Border; - hover: ColorPair; - } - - export interface Border extends ColorPair { - /** type of border ('line' or 'bg'). */ - type?: string; //'line'|'bg'; - /** character to use if bg type, default is space. */ - ch?: string; - } - - export interface Padding { - top?:number; - right?:number; - bottom?:number; - left?:number; - } - - export interface Position { - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - top?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - right?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - bottom?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - left?:number|string; - /** width of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - width?:number|string; - /** height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - height?:number|string; - } - - export interface KeyCode { - name: string; - ctrl: boolean; - meta: boolean; - shift: boolean; - sequence: string; - full: string; - } - - export class Program - { - /** - Wrap the given text in terminal formatting codes corresponding to the given attribute - name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 - integer color number. - */ - text (text:string, attr:string): string; - } - - export interface Colors { - /** Either pass a hex string, an array of 3 numbers, or three separate numbers representing an RGB value. This returns the 0-255 color number for that color. */ - match (r:string|number[]|number, g?:number, b?:number): number; - - /** An array of the 255 colors as hex strings. */ - colors: string[]; - } - - export interface NodeOptions - { - screen?: Screen; - parent?: Node; - children?: Node[]; - } - - export class Node extends events.EventEmitter - { - constructor(options?:NodeOptions); - - type : string; - options : NodeOptions; - parent : Node; - screen : Screen; - children : Node[]; - data : any; - _ : any; - $ : any; - index : number; - - // on(event:string, callback:() => void); - // on(event:'adopt', callback:() => void); - // on(event:'remove', callback:() => void); - // on(event:'reparent', callback:() => void); - // on(event:'attach', callback:() => void); - // on(event:'detach', callback:() => void); - - prepend(node:Node): void; - append(node:Node): void; - remove(node:Node): void; - insert(node:Node, index:number): void; - insertBefore(node:Node, refNode:Node): void; - insertAfter(node:Node, refNode:Node): void; - detach(): void; - // emitDescendants(): void; - // get(key:string): any; - // get(key:string, default:any): any; - // set(key:string, value:any): void; - } - - export interface ScreenOptions extends NodeOptions - { - /** the blessed Program to be associated with. will be automatically instantiated if none is provided. */ - program?: any; - /** attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with uniform cells to their sides). this is known to cause flickering with elements that are not full-width, however, it is more optimal for terminal rendering. */ - smartCSR?: boolean; - /** do CSR on any element within 20 cols of the screen edge on either side. faster than smartCSR, but may cause flickering depending on what is on each side of the element. */ - fastCSR?: boolean; - /** attempt to perform back_color_erase optimizations for terminals that support it. it will also work with terminals that don't support it, but only on lines with the default background color. as it stands with the current implementation, it's uncertain how much terminal performance this adds at the cost of overhead within node. */ - useBCE?: boolean; - /** amount of time (in ms) to redraw the screen after the terminal is resized (default: 300). */ - resizeTimeout?: number; - /** the width of tabs within an element's content. */ - tabSize?: number; - /** automatically position child elements with border and padding in mind. */ - autoPadding?: boolean; - /** the name of the logfile to use. if specified but the file does not exist, it will be created. see log method. */ - log?: string; - /** dump all output and input to desired file. can be used together with log option if set as a boolean. */ - dump?: any; - /** debug mode. enables usage of the `debug` method. also creates a debug console which will display when pressing F12. it will display all log and debug messages. */ - debug?: boolean; - /** Array of keys in their full format (e.g. C-c) to ignore when keys are locked. Useful for creating a key that will always exit no matter whether the keys are locked. */ - ignoreLocked?: string[]; - - /** Do not clear the screen, only scroll down enough to make room for the elements on the screen. do not use the alternate screenbuffer. useful for writing a CLI tool or some kind of prompt (experimental - see test/widget-noalt.js) */ - noAlt?: boolean; - - /** Options for the cursor. */ - cursor?: CursorOptions; - } - - export interface CursorOptions { - /** have blessed draw a custom cursor and hide the terminal cursor (experimental). */ - artificial?: boolean; - /** shape of the artificial cursor. can be: block, underline, or line. */ - shape?: string; //'block'|'underline'|'line'; - /** whether the artificial cursor blinks. */ - blink?: boolean; - /** color of the artificial cursor. accepts any valid color value (null is default). */ - color?: string; - } - - export interface ScreenEventCallback { - (character:string, keyCode:KeyCode): void; - } - - export class Screen extends Node - { - constructor(options?:ScreenOptions); - - /** the blessed Program object. */ - program: any; - /** the blessed Tput object (only available if you passed tput: true to the Program constructor.) */ - tput: any; - /** top of the focus history stack. */ - focused: any; - /** width of the screen (same as program.cols). */ - width: number; - /** height of the screen (same as program.rows). */ - height: number; - /** same as screen.width. */ - cols: number; - /** same as screen.height. */ - rows: number; - - /** calculated relative left offset. */ - left: number; - /** calculated relative right offset. */ - right: number; - /** calculated relative top offset. */ - top: number; - /** calculated relative bottom offset. */ - bottom: number; - /** calculated absolute left offset. */ - aleft: number; - /** calculated absolute right offset. */ - aright: number; - /** calculated absolute top offset. */ - atop: number; - /** calculated absolute bottom offset. */ - abottom: number; - - - /** whether the focused element grabs all keypresses. */ - grabKeys: boolean; - /** prevent keypresses from being received by any element. */ - lockKeys: boolean; - /** the currently hovered element. only set if mouse events are bound. */ - hover: Element; - /** set or get window title. */ - title: string; - - /** write string to the log file if one was created. */ - log(...msg:any[]): void; - /** same as the log method, but only gets called if the debug option was set. */ - debug(...msg:string[]): void; - /** allocate a new pending screen buffer and a new output screen buffer. */ - alloc(): void; - /** draw the screen based on the contents of the screen buffer. */ - draw(start:number, end:number): void; - /** render all child elements, writing all data to the screen buffer and drawing the screen. */ - render(): void; - /** clear any region on the screen. */ - clearRegion(x1:number, x2:number, y1:number, y2:number): void; - /** fill any region with a character of a certain attribute. */ - fillRegion(attr:number, ch:string, x1:number, x2:number, y1:number, y2:number): void; - /** focus element by offset of focusable elements. */ - focusOffset(offset:number): void; - /** focus previous element in the index. */ - focusPrevious(): void; - /** focus next element in the index. */ - focusNext(): void; - /** push element on the focus stack (equivalent to screen.focused = el). */ - focusPush(element:Element): void; - /** pop element off the focus stack. */ - focusPop(): void; - /** save the focused element. */ - saveFocus(): void; - /** restore the saved focused element. */ - restoreFocus(): void; - /** "rewind" focus to the last visible and attached element. */ - rewindFocus(): void; - /** bind a keypress listener for a specific key. */ - key(keyEvents:string|string[], callback:ScreenEventCallback): void; - /** bind a keypress listener for a specific key once. */ - onceKey(keyEvents:string|string[], callback:ScreenEventCallback): void; - /** remove a keypress listener for a specific key. */ - unkey(name:string, listener:ScreenEventCallback): void; - /** spawn a process in the foreground, return to blessed app after exit. */ - spawn(file:string, args:string[], options:NodeChildProcessExecOptions): child_process.ChildProcess; - /** spawn a process in the foreground, return to blessed app after exit. executes callback on error or exit. */ - exec(file:string, args:string[], options:NodeChildProcessExecOptions, callback:GenericCallback): child_process.ChildProcess; - /** read data from text editor. */ - readEditor(options:{}, callback:GenericCallback): void; - /** set effects based on two events and attributes. */ - setEffects(el:Element, fel:Element, over:string, out:string, effects:Style, temp?:string): void; - /** insert a line into the screen (using csr: this bypasses the output buffer). */ - insertLine(n:number, y:number, top:number, bottom:number): void; - /** delete a line from the screen (using csr: this bypasses the output buffer). */ - deleteLine(n:number, y:number, top:number, bottom:number): void; - /** insert a line at the bottom of the screen. */ - insertBottom(top:number, bottom:number): void; - /** insert a line at the top of the screen. */ - insertTop(top:number, bottom:number): void; - /** delete a line at the bottom of the screen. */ - deleteBottom(top:number, bottom:number): void; - /** delete a line at the top of the screen. */ - deleteTop(top:number, bottom:number): void; - - /** enable mouse events for the screen and optionally an element (automatically called when a form of on('mouse') is bound). */ - enableMouse(el?:Element): void; - /** enable keypress events for the screen and optionally an element (automatically called when a form of on('keypress') is bound). */ - enableKeys(el?:Element): void; - /** enable key and mouse events. calls bot enableMouse and enableKeys. */ - enableInput(el?:Element): void; - - /** attempt to copy text to clipboard using iTerm2's propriety sequence. returns true if successful. */ - copyToClipboard(text:string): boolean; - /** attempt to change cursor shape. will not work in all terminals (see artificial cursors for a solution to this). returns true if successful. */ - cursorShape(shape:string, blink:boolean): boolean; - /** attempt to change cursor color. returns true if successful. */ - cursorColor(color: string): boolean; - /** attempt to reset cursor. returns true if successful. */ - cursorReset(): boolean; - - } - - export interface ElementOptions extends NodeOptions - { - fg?: string; - bg?: string; - scrollbar?: ColorPair; - focus?: Style; - hover?: Style; - - /** border object, see below. */ - border?: Border; - /** positioning options. */ - position?: Position; - /** amount of padding on the inside of the element. can be a number or an object containing the properties: left, right, top, and bottom. */ - padding?: number|Padding; - /** element's text content. */ - content?: string; - /** element is clickable. */ - clickable?: boolean; - /** element is focusable and can receive key input. */ - input?: boolean; - /** element is focused. */ - focused?: boolean; - /** whether the element is hidden. */ - hidden?: boolean; - /** a simple text label for the element. */ - label?: string; - /** a floating text label for the element which appears on mouseover. */ - hoverText?: string; - /** text alignment: left, center, or right. */ - align?: string; - /** vertical text alignment: top, middle, or bottom. */ - valign?: string; - /** shrink/flex/grow to content and child elements. width/height during render. */ - shrink?: any; - /** width of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - width?: number|string; - /** height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - height?: number|string; - /** whether the element is scrollable or not. */ - scrollable?: boolean; - /** background character (default is whitespace ). */ - ch?: string; - /** allow the element to be dragged with the mouse. */ - draggable?: boolean; - } - - export class Element extends Node - { - constructor(options?:ElementOptions); - - /** name of the element. useful for form submission. */ - name: string; - /** border object. */ - border: Border; - /** contains attributes (e.g. fg/bg/underline). see above. */ - style: Style; - /** raw width, height, and offsets. */ - position: Position; - /** type of border (line or bg). bg by default. */ - type: string; //'line'|'bg'; - /** character to use if bg type, default is space. */ - ch: string; - /** raw text content. */ - content: string; - /** whether the element is hidden or not. */ - hidden: boolean; - /** whether the element is visible or not. */ - visible: boolean; - /** whether the element is attached to a screen in its ancestry somewhere. */ - detached: boolean; - /** calculated width. */ - width: number; - /** calculated height. */ - height: number; - /** whether the element is draggable. set to true to allow dragging. */ - draggable: boolean; - - - - /** calculated relative left offset. */ - left: number; - /** calculated relative right offset. */ - right: number; - /** calculated relative top offset. */ - top: number; - /** calculated relative bottom offset. */ - bottom: number; - /** calculated absolute left offset. */ - aleft: number; - /** calculated absolute right offset. */ - aright: number; - /** calculated absolute top offset. */ - atop: number; - /** calculated absolute bottom offset. */ - abottom: number; - - - /** write content and children to the screen buffer. */ - render(): void; - /** hide element. */ - hide(): void; - /** show element. */ - show(): void; - /** toggle hidden/shown. */ - toggle(): void; - /** focus element. */ - focus(): void; - /** bind a keypress listener for a specific key. */ - key(name:string|string[], listener:(character?:any, keyCode?:any) => void): void; - /** bind a keypress listener for a specific key once. */ - onceKey(name:string, listener:() => void): void; - /** remove a keypress listener for a specific key. */ - unkey(name:string, listener:() => void): void; - /** same as el.on('screen', ...) except this will automatically cleanup listeners after the element is detached. */ - onScreenEvent(event:string, listener:(...args:any[]) => void): void; - /** set the z-index of the element (changes rendering order). */ - setIndex(z:number): void; - /** put the element in front of its siblings. */ - setFront(): void; - /** put the element in back of its siblings. */ - setBack(): void; - /** set the label text for the top-left corner. example options: {text:'foo',side:'left'} */ - setLabel(textOrOptions:string|{}): void; - /** remove the label completely. */ - removeLabel(): void; - /** set the hover text for the bottom-right corner. example options: {text:'foo'} */ - setHover(textOrOptions:string|{}): void; - /** remove the hover label completely. */ - removeHover(): void; - /** set the content. note: when text is input, it will be stripped of all non-SGR escape codes, tabs will be replaced with 8 spaces, and tags will be replaced with SGR codes (if enabled). */ - setContent(text:string): void; - /** return content, slightly different from el.content. assume the above formatting. */ - getContent(): void; - /** similar to setContent, but ignore tags and remove escape codes. */ - setText(text:string): void; - /** similar to getContent, but return content with tags and escape codes removed. */ - getText(): void; - /** insert a line into the box's content. */ - insertLine(index:number, lines:string|string[]): void; - /** delete a line from the box's content. */ - deleteLine(index:number, numLines:number): void; - /** get a line from the box's content. */ - getLine(index:number): void; - /** get a line from the box's content from the visible top. */ - getBaseLine(index:number): void; - /** set a line in the box's content. */ - setLine(index:number, line:string): void; - /** set a line in the box's content from the visible top. */ - setBaseLine(index:number, line:string): void; - /** clear a line from the box's content. */ - clearLine(index:number): void; - /** clear a line from the box's content from the visible top. */ - clearBaseLine(index:number): void; - /** insert a line at the top of the box. */ - insertTop(lines:string|string[]): void; - /** insert a line at the bottom of the box. */ - insertBottom(lines:string|string[]): void; - /** delete a line at the top of the box. */ - deleteTop(): void; - /** delete a line at the bottom of the box. */ - deleteBottom(): void; - /** unshift a line onto the top of the content. */ - unshiftLine(lines:string|string[]): void; - /** shift a line off the top of the content. */ - shiftLine(index:number): void; - /** push a line onto the bottom of the content. */ - pushLine(lines:string|string[]): void; - /** pop a line off the bottom of the content. */ - popLine(index:number): void; - /** an array containing the content lines. */ - getLines(): void; - /** an array containing the lines as they are displayed on the screen. */ - getScreenLines(): void; - /** get a string's real length, taking into account tags. */ - textLength(text:string): number; - - /** enable dragging of the element. */ - enableDrag(): void; - /** disable dragging of the element. */ - disableDrag(): void; - } - - - // - // Box - // - - export interface BoxOptions extends ElementOptions { - // intentionally empty - } - - export class Box extends Element { - constructor(options?:BoxOptions); - // intentionally empty - } - - - // - // ScrollableBox - // - - export interface ScrollableBoxOptions extends BoxOptions { - /** a limit to the childBase. default is `Infinity`. */ - baseLimit: number; - /** a option which causes the ignoring of `childOffset`. this in turn causes the childBase to change every time the element is scrolled. */ - alwaysScroll: boolean; - /** object enabling a scrollbar. */ - scrollbar: ScrollBar; - } - - /** A box with scrollable content. */ - export class ScrollableBox extends Box { - constructor(options?:ScrollableBoxOptions); - - /** the offset of the top of the scroll content. */ - childBase: number; - /** the offset of the chosen item/line. */ - childOffset: number; - /** scroll the content by a relative offset. */ - scroll(offset:number): void; - /** scroll the content to an absolute index. */ - scrollTo(index:number): void; - /** same as `scrollTo`. */ - setScroll(index:number): void; - /** set the current scroll index in percentage (0-100). */ - setScrollPerc(perc:number): void; - /** get the current scroll index in lines. */ - getScroll(): number; - /** get the actual height of the scrolling area. */ - getScrollHeight(): number; - /** get the current scroll index in percentage. */ - getScrollPerc(): number; - /** reset the scroll index to its initial state. */ - resetScroll(): void; - - } - - export interface ScrollBar { - /** style of the scrollbar. */ - style: Style; - /** style of the scrollbar track if present (takes regular style options). */ - track: Style; - } - - - // - // ScrollableText - // - - export interface ScrollableTextOptions extends ScrollableBoxOptions { - /** whether to enable automatic mouse support for this element. */ - mouse: boolean; - /** use predefined keys for navigating the text. */ - keys: boolean; - /** use vi keys with the `keys` option. */ - vi: boolean; - } - - /** __DEPRECATED__ - Use Box with the `scrollable` and `alwaysScroll` options instead. A scrollable text box which can display and scroll text, as well as handle pre-existing newlines and escape codes. */ - export class ScrollableText extends ScrollableBox { - constructor(options?:ScrollableTextOptions); - } - - - - // - // Text - // - - export interface TextOptions extends ElementOptions { - align?: string; //'left'|'center'|'right'; - } - - export class Text extends Element { - constructor(options?:TextOptions); - // intentionally empty - } - - - // - // Line - // - - export interface LineOptions extends BoxOptions { - orientation?: string; //'vertical'|'horizontal'; - style?: Style; - } - - export class Line extends Box { - constructor(options?:LineOptions); - // intentionally empty - } - - - // - // List - // - - export interface ListStyle extends Style { - selected?: Style; - item?: Style; - } - - export interface ListOptions extends BoxOptions - { - style?: ListStyle; - - /** whether to automatically enable mouse support for this list (allows clicking items). */ - mouse?: boolean; - /** use predefined keys for navigating the list. */ - keys?: any; - /** use vi keys with the keys option. */ - vi?: boolean; - /** an array of strings which become the list's items. */ - items?: string[]; - /** a function that is called when vi mode is enabled and the key / is pressed. This function accepts a callback function which should be called with the search string. The search string is then used to jump to an item that is found in items. */ - search?: (callback:(searchString:string) => void) => void; - /** whether the list is interactive and can have items selected (default: true). */ - interactive?: boolean; - } - - export class List extends Box - { - constructor(options?:ListOptions); - - /** The text of the currently selected item. */ - value:string; - /** The items in the list. */ - items:string[]; - /** The items in the list. */ - ritems:string[]; - /** The index of the current selection. */ - selected:number; - - /** add an item based on a string. */ - addItem(text:string): void; - /** returns the item index from the list. child can be an element, index, or string. */ - getItemIndex(child:Element|number|string): void; - /** returns the item element. child can be an element, index, or string. */ - getItem(child:Element|number|string): void; - /** removes an item from the list. child can be an element, index, or string. */ - removeItem(child:Element|number|string): void; - /** clears all items from the list. */ - clearItems(): void; - /** sets the list items to multiple strings. */ - setItems(items:string[]): void; - /** Sets the current selection by absolute index. */ - select(index:number): void; - /** Changes the current selection based on current offset. */ - move(offset:number): void; - /** select item above selected. */ - up(amount:number): void; - /** select item below selected. */ - down(amount:number): void; - /** show/focus list and pick an item. the callback is executed with the result. */ - pick(cwd:string, callback:(err:any, file:string) => void): void; - - /** show/focus list and pick an item. the callback is executed with the result. */ - pick(callback:(err:any, file:string) => void): void; - } - - // - // Input - // - - export interface InputOptions extends BoxOptions { - // intentionally empty - } - - export class Input extends Box { - constructor(options?:InputOptions); - // intentionally empty - } - - export interface InputOptions extends BoxOptions { - // intentionally empty - } - - // - // Textarea - // - - export interface TextareaOptions extends InputOptions - { - /** use pre-defined keys (`i` or `enter` for insert, `e` for editor, `C-e` for editor while inserting). */ - keys?: boolean; - /** use pre-defined mouse events (right-click for editor). */ - mouse?: boolean; - /** call `readInput()` when the element is focused. automatically unfocus. */ - inputOnFocus?: boolean; - } - - /** A box which allows multiline text input. */ - export class Textarea extends Input - { - constructor(options?:TextareaOptions); - - /** the input text. __read-only__. */ - value: string; - - /** submit the textarea (emits `submit`). */ - submit(): void; - /** cancel the textarea (emits `cancel`). */ - cancel(): void; - /** grab key events and start reading text from the keyboard. takes a callback which receives the final value. */ - readInput(callback:GenericCallback): void; - /** open text editor in `$EDITOR`, read the output from the resulting file. takes a callback which receives the final value. */ - readEditor(callback:GenericCallback): void; - /** the same as `this.value`, for now. */ - getValue(): string; - /** clear input. */ - clearValue(): void; - /** set value. */ - setValue(text:string): void; - } - - - // - // Textbox - // - - export interface TextboxOptions extends TextareaOptions { - /** completely hide text. */ - secret?: boolean; - /** replace text with asterisks (`*`). */ - censor?: boolean; - } - - /** A box which allows text input. */ - export class Textbox extends Textarea { - constructor(options?:TextboxOptions); - - /** completely hide text. */ - secret: boolean; - /** replace text with asterisks (`*`). */ - censor: boolean; - } - - - // - // Button - // - - export interface ButtonOptions extends InputOptions { - } - - /** A button which can be focused and allows key and mouse input. */ - export class Button extends Input { - constructor(options?:ButtonOptions); - - // on(event:string, callback:() => void): void; - // on(event:'press', callback:() => void); - - /** press button. emits 'press'. */ - press(): void; - } - - - // - // ProgressBar - // - - export interface ProgressBarOptions extends InputOptions { - /** can be `horizontal` or `vertical`. */ - orientation: string; - /** the character to fill the bar with (default is space). */ - pch: string; - /** the amount filled (0 - 100). */ - filled: number; - /** same as `filled`. */ - value: number; - /** enable key support. */ - keys: boolean; - /** enable mouse support. */ - mouse: boolean; - - /** contains the extra key 'bar', which defines the style of the bar contents itself. */ - style: ProgressBarStyle; - } - - export interface ProgressBarStyle extends Style { - /** style of the bar contents itself. */ - bar: Style; - } - - - export class ProgressBar extends Input { - constructor(options?:ProgressBarOptions); - - /** progress the bar by a fill amount. */ - progress(amount:number): void; - /** set progress to specific amount. */ - setProgress(amount:number): void; - /** reset the bar. */ - reset(): void; - } - - // - // Checkbox - // - - export interface CheckboxOptions extends InputOptions { - /** whether the element is checked or not. */ - checked: boolean; - /** enable mouse support. */ - mouse: boolean; + export module Events { + + export interface IMouseEventArg { + x: number; + y: number; + action: Types.TMouseAction; + } + + export interface IKeyEventArg { + full: string; + name: string; + shift: boolean; + ctrl: boolean; + meta: boolean; + sequence: string; + } } - - /** A checkbox which can be used in a form element. */ - export class Checkbox extends Input - { - constructor(options?:CheckboxOptions); - - /** the text next to the checkbox (do not use setcontent, use `check.text = ''`). */ - text: string; - /** whether the element is checked or not. */ - checked: boolean; - /** same as `checked`. */ - value: boolean; - - /** check the element. */ - check(): void; - /** uncheck the element. */ - uncheck(): void; - /** toggle checked state. */ - toggle(): void; - } - - - // - // RadioSet - // - - export interface RadioSetOptions extends BoxOptions { - } - - - export class RadioSet extends Box { - constructor(options?:RadioSetOptions); - } - - - // - // RadioButton - // - - export interface RadioButtonOptions extends CheckboxOptions { - } - - - /** A radio button which can be used in a form element. */ - export class RadioButton extends Checkbox { - constructor(options?:RadioButtonOptions); - } - - - - // - // Prompt - // - - export interface PromptOptions extends BoxOptions { - } - - - /** A prompt box containing a text input, okay, and cancel buttons (automatically hidden). */ - export class Prompt extends Box - { - constructor(options?:PromptOptions); - - /** show the prompt and wait for the result of the textbox. set text and initial value */ - input(text:string, value:any, callback:(val:any) => void): void; - /** show the prompt and wait for the result of the textbox. set text and initial value */ - setInput(text:string, value:any, callback:(val:any) => void): void; - /** show the prompt and wait for the result of the textbox. set text and initial value */ - readInput(text:string, value:any, callback:(val:any) => void): void; - } - - - // - // Question - // - - export interface QuestionOptions extends BoxOptions { - } - - - /** A question box containing okay and cancel buttons (automatically hidden). */ - export class Question extends Box - { - constructor(options?:QuestionOptions); - - /** ask a `question`. `callback` will yield the result. */ - ask(question:string, callback:(result:any) => void): void; - } - - - // - // Message - // - - export interface MessageOptions extends BoxOptions { - } - - - /** A box containing a message to be displayed (automatically hidden). */ - export class Message extends Box - { - constructor(options?:MessageOptions); - - /** display a message for a time (default is 3 seconds). set time to 0 for a perpetual message that is dismissed on keypress. */ - log(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - /** display a message for a time (default is 3 seconds). set time to 0 for a perpetual message that is dismissed on keypress. */ - display(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - /** display an error in the same way. */ - error(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - } - - export interface MessageCallback { - (): void; - } - - - // - // Loading - // - - export interface LoadingOptions extends BoxOptions { - } - - /** A box with a spinning line to denote loading (automatically hidden). */ - export class Loading extends Box - { - constructor(options?:LoadingOptions); - - /** display the loading box with a message. will lock keys until `stop` is called. */ - load(text:string): void; - /** hide loading box. unlock keys. */ - stop(): void; - } - - - // - // Listbar - // - - export interface ListbarOptions extends BoxOptions - { - /** Listbar's `style` object includes sub-styles for `selected` and `item`. */ - style?: ListbarStyle; - - /** set buttons using an object with keys as titles of buttons, containing of objects containing keys of `keys` and `callback`. */ - items?: ListbarItemSet; - /** set buttons using an object with keys as titles of buttons, containing of objects containing keys of `keys` and `callback`. */ - commands?: ListbarItemSet; - /** automatically bind list buttons to keys 0-9. */ - autoCommandKeys?: boolean; - } - - export interface ListbarItemSet { - [name: string]: ListbarItem; - } - - export interface ListbarItem { - keys: string[]; - callback: GenericCallback; - } - - export interface ListbarStyle extends Style - { - /** style for a selected item. */ - selected: Style; - /** style for an unselected item. */ - item: Style; - } - - /** A horizontal list. Useful for a main menu bar. */ - export class Listbar extends Box - { - constructor(options?:ListbarOptions); - - /** append an item to the bar. */ - add(item:ListbarItem, callback:GenericCallback): void; - /** append an item to the bar. */ - addItem(item:ListbarItem, callback:GenericCallback): void; - /** append an item to the bar. */ - appendItem(item:ListbarItem, callback:GenericCallback): void; - - /** select button and execute its callback. */ - selectTab(index: number): void; - - /** set commands (see `commands` option above). */ - setItems(commands: ListbarItemSet): void; - /** select an item on the bar. */ - select(offset: number): void; - /** remove item from the bar. */ - removeItem(child:ListbarItem): void; - /** move focus relatively across the bar. */ - move(offset: number): void; - /** move focus left relatively across the bar. */ - moveLeft(offset: number): void; - /** move focus right relatively across the bar. */ - moveRight(offset: number): void; - } - - - // - // Log - // - - export interface LogOptions extends ScrollableTextOptions { - /** amount of scrollback allowed. default: Infinity. */ - scrollback?: number; - /** scroll to bottom on input even if the user has scrolled up. default: false. */ - scrollOnInput?: boolean; - } - - - /** A log permanently scrolled to the bottom. */ - export class Log extends ScrollableText - { - constructor(options?:LogOptions); - - /** amount of scrollback allowed. default: Infinity. */ - scrollback: number; - /** scroll to bottom on input even if the user has scrolled up. default: false. */ - scrollOnInput: boolean; - - /** add a log line. */ - log(text:string): void; - /** add a log line. */ - add(text:string): void; - } - - - // - // Table - // - - export interface TableOptions extends BoxOptions - { - /** array of array of strings representing rows (same as `data`). */ - rows?: string[][]; - /** array of array of strings representing rows (same as `rows`). */ - data?: string[][]; - /** spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). */ - pad?: number; - /** do not draw inner cells. */ - noCellBorders?: boolean; - /** fill cell borders with the adjacent background color. */ - fillCellBorders?: boolean; - - /** includes `header` and `cell` substyles. */ - style?: TableStyle; - } - - export interface TableStyle extends Style { - /** header style. */ - header: Style; - /** cell style. */ - cell: Style; - } - - /** A stylized table of text elements. */ - export class Table extends Box - { - /** includes `header` and `cell` substyles. */ - style: TableStyle; - - /** set rows in table. array of arrays of strings. */ - setData(rows: string[][]): void; - /** set rows in table. array of arrays of strings. */ - setRows(rows: string[][]): void; - } - - - // - // ListTable - // - - export interface ListTableOptions extends ListOptions - { - /** array of array of strings representing rows (same as `data`). */ - rows?: string[][]; - /** array of array of strings representing rows (same as `rows`). */ - data?: string[][]; - /** spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). */ - pad?: number; - - /** do not draw inner cells. */ - noCellBorders?: boolean; - - /** includes `header` and `cell` substyles. */ - style?: TableStyle; - } - - export interface ListTableStyle extends TableStyle { - } - - - /** A stylized table of text elements with a list. */ - export class ListTable extends List - { - constructor(options?:ListTableOptions); - - /** set rows in table. array of arrays of strings. */ - setData(rows: string[][]): void; - /** set rows in table. array of arrays of strings. */ - setRows(rows: string[][]): void; - } - - // - // Image - // - - export interface ImageOptions extends BoxOptions { - /** path to image. */ - file: string; - /** path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. */ - w3m: string; - } - - - /** Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. */ - export class Image extends Box - { - constructor(options?:ImageOptions); - - /** set the image in the box to a new path. */ - setImage (img:string, callback:GenericCallback): void; - /** clear the current image. */ - clearImage (callback:GenericCallback): void; - /** get the size of an image file in pixels. */ - imageSize (img:string, callback:GenericCallback): void; - /** get the size of the terminal in pixels. */ - termSize (callback:GenericCallback): void; - /** get the pixel to cell ratio for the terminal. */ - getPixelRatio (callback:GenericCallback): void; - } - - - // - // Form - // - - export interface FormOptions extends BoxOptions { - /** allow default keys (tab, vi keys, enter). */ - keys?:boolean; - /** allow vi keys. */ - vi?:boolean; - } - - export class Form extends Box - { - constructor(options?:FormOptions); - - /** last submitted data. */ - submission: any; - - // on(event:string, callback:() => void): void; - // on(event:'submit', callback:(data) => void): void; - // on(event:'cancel', callback:() => void): void; - // on(event:'reset', callback:() => void): void; - - next(): void; - previous(): void; - - resetSelected(): void; - /** focus first form element. */ - focusFirst(): void; - /** focus last form element. */ - focusLast(): void; - /** focus next form element. */ - focusNext(): void; - /** focus previous form element. */ - focusPrevious(): void; - /** submit the form. */ - submit(): void; - /** discard the form. */ - cancel(): void; - /** clear the form. */ - reset(): void; - } - - - // - // FileManager - // - - export interface FileManagerOptions extends ListOptions { - cwd?: string; - } - - export interface DirectoryEntry { - name: string; - text: string; - dir: boolean; - symlink: boolean; - } - - export class FileManager extends List - { - constructor(options?:FileManagerOptions); - - cwd: string; - - useFormatter (formatterFn:(entry:DirectoryEntry) => DirectoryEntry): void; - - /** refresh the file list (perform a readdir on cwd and update the list items). */ - refresh (cwd?:string, callback?:() => void): void; - - /** refresh the file list. */ - refresh (callback?:() => void): void; - - /** reset back to original cwd. */ - reset (cwd?:string, callback?:() => void): void; - } - - - // - // Terminal - // - - export interface TerminalOptions extends BoxOptions - { - /** handler for input data. */ - handler?: (userInput:Buffer) => void; - /** name of shell. $SHELL by default. */ - shell?:string; - /** args for shell. */ - args?:any; - /** can be line, underline, and block. */ - cursor?:string; //'line'|'underline'|'block'; - } - - export class Terminal extends Box - { - /** reference to the headless term.js terminal. */ - term: any; - /** reference to the pty.js pseudo terminal. */ - pty: any; - - /** write data to the terminal. */ - write(data:string): void; - - /** nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. */ - screenshot(xi?:number, xl?:number, yi?:number, yl?:number): string; - } - - - export interface NodeChildProcessExecOptions - { + export interface NodeChildProcessExecOptions { cwd?: string; stdio?: any; customFds?: any; @@ -1260,10 +159,2676 @@ declare module "blessed" maxBuffer?: number; killSignal?: string; } + + export interface IDestroyable { + destroy(): void; + } + + export interface IOptions { + } + + export interface IHasOptions { + options: T; + } + + export interface TputsOptions extends IOptions { + terminal?: string; + extended?: boolean; + debug?: boolean; + termcap?: string; + terminfoFile?: string; + terminfoPrefix?: string; + termcapFile?: string; + } + + export class Tput implements IHasOptions { + constructor(opts: TputsOptions); + + // ** properties ** // + + /** + * Original options object. + */ + options: TputsOptions; + + debug: boolean; + padding: boolean; + extended: boolean; + printf: boolean; + termcap: string; + terminfoPrefix: string; + terminfoFile: string; + termcapFile: string; + error: Error; + terminal: string; + + setup(): void; + term(is: any): boolean; + readTerminfo(term: string): string; + parseTerminfo(data: any, file: string): { + header: { + dataSize: number; + headerSize: number; + magicNumber: boolean; + namesSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + extended: { + dataSize: number; + headerSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + lastStrTableOffset: number; + } + } + name: string; + names: string[]; + desc: string; + bools: Object; + numbers: Object; + strings: Object; + }; + } + + export interface IDestroyable { + destroy(): void; + } + + export interface INodeOptions extends IOptions { + name?: string; + screen?: Screen; + parent?: Node; + children?: Node[]; + focusable?: boolean; + } + + export abstract class Node extends EventEmitter implements IHasOptions, IDestroyable { + constructor(options: INodeOptions); + + // ** properties ** // + + focusable: boolean; + + /** + * Original options object. + */ + options: INodeOptions; + + /** + * An object for any miscellanous user data. + */ + data: {[index: string]: any;}; + /** + * An object for any miscellanous user data. + */ + _: {[index: string]: any;}; + /** + * An object for any miscellanous user data. + */ + $: {[index: string]: any;}; + /** + * Type of the node (e.g. box). + */ + type: string; + /** + * Render index (document order index) of the last render call. + */ + index: number; + /** + * Parent screen. + */ + screen: Screen; + /** + * Parent node. + */ + parent: Node; + /** + * Array of node's children. + */ + children: Node[]; + + // ** methods ** // + + /** + * Prepend a node to this node's children. + */ + prepend(node: Node): void; + /** + * Append a node to this node's children. + */ + append(node: Node): void; + /** + * Remove child node from node. + */ + remove(node: Node): void; + /** + * Insert a node to this node's children at index i. + */ + insert(node: Node, index: number): void; + /** + * Insert a node to this node's children before the reference node. + */ + insertBefore(node: Node, refNode: Node): void; + /** + * Insert a node from node after the reference node. + */ + insertAfter(node: Node, refNode: Node): void; + /** + * Remove node from its parent. + */ + detach(): void; + /** + * Remove node from its parent. + */ + free(): void; + /** + * Remove node from its parent. + */ + forDescendants(iter: Function, s: any): void; + /** + * Remove node from its parent. + */ + forAncestors(iter: Function, s: any): void; + /** + * Remove node from its parent. + */ + collectDescendants(s: any): void; + /** + * Remove node from its parent. + */ + collectAncestors(s: any): void; + /** + * Remove node from its parent. + */ + emitDescendants(): void; + /** + * Remove node from its parent. + */ + emitAncestors(): void; + /** + * Remove node from its parent. + */ + hasDescendant(target: Node): void; + /** + * Remove node from its parent. + */ + hasAncestor(target: Node): boolean; + /** + * Remove node from its parent. + */ + destroy(): void; + /** + * Emit event for element, and recursively emit same event for all descendants. + */ + emitDescendants(type: string, ...args: any[]): void; + /** + * Get user property with a potential default value. + */ + get(name: string, def: T): T; + /** + * Set user property to value. + */ + set(name: string, value: T): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when node is added to a parent. + */ + on(event: "adopt", callback: (arg: Node) => void): this; + /** + * Received when node is removed from it's current parent. + */ + on(event: "remove", callback: (arg: Node) => void): this; + /** + * Received when node gains a new parent. + */ + on(event: "reparent", callback: (arg: Node) => void): this; + /** + * Received when node is attached to the screen directly or somewhere in its ancestry. + */ + on(event: "attach", callback: (arg: Node) => void): this; + /** + * Received when node is detached from the screen directly or somewhere in its ancestry. + */ + on(event: "detach", callback: (arg: Node) => void): this; + } + + export class NodeWithEvents extends Node { + // ** methods ** // + + /** + * Bind a keypress listener for a specific key. + */ + key(name: string | string[], listener: Function): void; + /** + * Bind a keypress listener for a specific key once. + */ + onceKey(name: string, listener: Function): void; + /** + * Remove a keypress listener for a specific key. + */ + unkey(name: string, listener: Function): void; + removeKey(name: string, listener: Function): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received on screen resize. + */ + on(event: "resize", callback: () => void): this; + /** + * Received on mouse events. + */ + on(event: "mouse", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseout", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseover", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousedown", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseup", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousewheel", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "wheeldown", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "wheelup", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousemove", callback: (arg: Events.IMouseEventArg) => void): this; + /** + * Received on key events. + */ + on(event: "keypress", callback: (ch: string, key: Events.IKeyEventArg) => void): this; + /** + * Global events received for all elements. + */ + on(event: "element click", callback: (arg: Screen) => void): this; + on(event: "element mouseover", callback: (arg: Screen) => void): this; + on(event: "element mouseout", callback: (arg: Screen) => void): this; + on(event: "element mouseup", callback: (arg: Screen) => void): this; + /** + * Received on key event for [name]. + */ + //on(event: "key", callback: (arg: BlessedScreen) => void): this; + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + on(event: "focus", callback: (arg: Screen) => void): this; + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + on(event: "blur", callback: (arg: Screen) => void): this; + /** + * Received before render. + */ + on(event: "prerender", callback: () => void): this; + /** + * Received on render. + */ + on(event: "render", callback: () => void): this; + /** + * Received when blessed notices something untoward (output is not a tty, terminfo not found, etc). + */ + on(event: "warning", callback: (text: string) => void): this; + /** + * Received when the screen is destroyed (only useful when using multiple screens). + */ + on(event: "destroy", callback: () => void): this; + /** + * Received when the element is moved. + */ + on(event: "move", callback: () => void): this; + /** + * Element was clicked (slightly smarter than mouseup). + */ + on(event: "click", callback: (arg: Screen) => void): this; + /** + * Received when element is shown. + */ + on(event: "show", callback: () => void): this; + /** + * Received when element becomes hidden. + */ + on(event: "hide", callback: () => void): this; + + on(event: "set content", callback: () => void): this; + on(event: "parsed content", callback: () => void): this; + } + + export interface IScreenOptions extends INodeOptions { + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program?: BlessedProgram; + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR?: boolean; + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR?: boolean; + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE?: boolean; + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout?: number; + /** + * The width of tabs within an element's content. + */ + tabSize?: number; + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding?: boolean; + + cursor?: Types.TCursor; + + /** + * Create a log file. See log method. + */ + log?: (...msg: any[]) => void; + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump?: string; + /** + * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when + * pressing F12. It will display all log and debug messages. + */ + debug?: (...msg: string[]) => void; + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked?: boolean; + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders?: boolean; + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast?: boolean; + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode?: boolean; + /** + * Send focus events after mouse is enabled. + */ + sendFocus?: boolean; + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings?: boolean; + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode?: boolean; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + input?: stream.Writable; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + output?: stream.Readable; + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput?: Tput; + /** + * Top of the focus history stack. + */ + focused?: BlessedElement; + /** + * Width of the screen (same as program.cols). + */ + width?: Types.TPosition; + /** + * Height of the screen (same as program.rows). + */ + height?: Types.TPosition; + /** + * Same as screen.width. + */ + cols?: number; + /** + * Same as screen.height. + */ + rows?: number; + /** + * Relative top offset, always zero. + */ + top?: Types.TTopLeft; + /** + * Relative left offset, always zero. + */ + left?: Types.TTopLeft; + /** + * Relative right offset, always zero. + */ + right?: Types.TPosition; + /** + * Relative bottom offset, always zero. + */ + bottom?: Types.TPosition; + /** + * Absolute top offset, always zero. + */ + atop?: Types.TTopLeft; + /** + * Absolute left offset, always zero. + */ + aleft?: Types.TTopLeft; + /** + * Absolute right offset, always zero. + */ + aright?: Types.TPosition; + /** + * Absolute bottom offset, always zero. + */ + abottom?: Types.TPosition; + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys?: any; + /** + * Prevent keypresses from being received by any element. + */ + lockKeys?: boolean; + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover?: any; + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal?: string; + /** + * Set or get window title. + */ + title?: string; + } + + export class Screen extends NodeWithEvents implements IHasOptions { + constructor(opts: IScreenOptions); + + // ** properties ** // + cleanSides: any; + + /** + * Original options object. + */ + options: IScreenOptions; + + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program: BlessedProgram; + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR: boolean; + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR: boolean; + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE: boolean; + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout: number; + /** + * The width of tabs within an element's content. + */ + tabSize: number; + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding: boolean; + + cursor: Types.TCursor; + + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump: string; + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked: boolean; + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders: boolean; + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast: boolean; + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode: boolean; + /** + * Send focus events after mouse is enabled. + */ + sendFocus: boolean; + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings: boolean; + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode: boolean; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + input: stream.Writable; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + output: stream.Readable; + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput: Tput; + /** + * Top of the focus history stack. + */ + focused: BlessedElement; + /** + * Width of the screen (same as program.cols). + */ + width: Types.TPosition; + /** + * Height of the screen (same as program.rows). + */ + height: Types.TPosition; + /** + * Same as screen.width. + */ + cols: number; + /** + * Same as screen.height. + */ + rows: number; + /** + * Relative top offset, always zero. + */ + top: Types.TTopLeft; + /** + * Relative left offset, always zero. + */ + left: Types.TTopLeft; + /** + * Relative right offset, always zero. + */ + right: Types.TPosition; + /** + * Relative bottom offset, always zero. + */ + bottom: Types.TPosition; + /** + * Absolute top offset, always zero. + */ + atop: Types.TTopLeft; + /** + * Absolute left offset, always zero. + */ + aleft: Types.TTopLeft; + /** + * Absolute right offset, always zero. + */ + aright: Types.TPosition; + /** + * Absolute bottom offset, always zero. + */ + abottom: Types.TPosition; + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys: any; + /** + * Prevent keypresses from being received by any element. + */ + lockKeys: boolean; + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover: any; + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal: string; + /** + * Set or get window title. + */ + title: string; + + // ** methods ** // + + /** + * Write string to the log file if one was created. + */ + log(...msg: any[]): void; + /** + * Same as the log method, but only gets called if the debug option was set. + */ + debug(...msg: string[]): void; + /** + * Allocate a new pending screen buffer and a new output screen buffer. + */ + alloc(): void; + /** + * Reallocate the screen buffers and clear the screen. + */ + realloc(): void; + /** + * Draw the screen based on the contents of the screen buffer. + */ + draw(start: number, end: number): void; + /** + * Render all child elements, writing all data to the screen buffer and drawing the screen. + */ + render(): void; + /** + * Clear any region on the screen. + */ + clearRegion(x1: number, x2: number, y1: number, y2: number): void; + /** + * Fill any region with a character of a certain attribute. + */ + fillRegion(attr: string, ch: string, x1: number, x2: number, y1: number, y2: number): void; + /** + * Focus element by offset of focusable elements. + */ + focusOffset(offset: number): any; + /** + * Focus previous element in the index. + */ + focusPrevious(): void; + /** + * Focus next element in the index. + */ + focusNext(): void; + /** + * Push element on the focus stack (equivalent to screen.focused = el). + */ + focusPush(element: BlessedElement): void; + /** + * Pop element off the focus stack. + */ + focusPop(): BlessedElement; + /** + * Save the focused element. + */ + saveFocus(): BlessedElement; + /** + * Restore the saved focused element. + */ + restoreFocus(): BlessedElement; + /** + * "Rewind" focus to the last visible and attached element. + */ + rewindFocus(): BlessedElement; + /** + * Spawn a process in the foreground, return to blessed app after exit. + */ + spawn(file: string, args: string[], options: NodeChildProcessExecOptions): child_process.ChildProcess; + /** + * Spawn a process in the foreground, return to blessed app after exit. Executes callback on error or exit. + */ + exec(file: string, args: string[], options: NodeChildProcessExecOptions, callback: Function): child_process.ChildProcess; + /** + * Read data from text editor. + */ + readEditor(options: any, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + readEditor(callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /** + * Set effects based on two events and attributes. + */ + setEffects(el: BlessedElement, fel: BlessedElement, over: any, out: any, effects: any, temp: any): void; + /** + * Insert a line into the screen (using csr: this bypasses the output buffer). + */ + insertLine(n: number, y: number, top: number, bottom: number): void; + /** + * Delete a line from the screen (using csr: this bypasses the output buffer). + */ + deleteLine(n: number, y: number, top: number, bottom: number): void; + /** + * Insert a line at the bottom of the screen. + */ + insertBottom(top: number, bottom: number): void; + /** + * Insert a line at the top of the screen. + */ + insertTop(top: number, bottom: number): void; + /** + * Delete a line at the bottom of the screen. + */ + deleteBottom(top: number, bottom: number): void; + /** + * Delete a line at the top of the screen. + */ + deleteTop(top: number, bottom: number): void; + /** + * Enable mouse events for the screen and optionally an element (automatically called when a form of + * on('mouse') is bound). + */ + enableMouse(el: BlessedElement): void; + enableMouse(): void; + /** + * Enable keypress events for the screen and optionally an element (automatically called when a form of + * on('keypress') is bound). + */ + enableKeys(el: BlessedElement): void; + enableKeys(): void; + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(el: BlessedElement): void; + enableInput(): void; + /** + * Attempt to copy text to clipboard using iTerm2's proprietary sequence. Returns true if successful. + */ + copyToClipboard(text: string): void; + /** + * Attempt to change cursor shape. Will not work in all terminals (see artificial cursors for a solution + * to this). Returns true if successful. + */ + cursorShape(shape: boolean, blink: boolean): any; + /** + * Attempt to change cursor color. Returns true if successful. + */ + cursorColor(color: string): void; + /** + * Attempt to reset cursor. Returns true if successful. + */ + cursorReset(): void; + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + /** + * Destroy the screen object and remove it from the global list. Also remove all global events relevant + * to the screen object. If all screen objects are destroyed, the node process is essentially reset + * to its initial state. + */ + destroy(): void; + /** + * Reset the terminal to term. Reloads terminfo. + */ + setTerminal(term: string): void; + } + + export interface Padding { + left?: number; + right?: number; + top?: number; + bottom?: number; + } + + export class PositionCoords { + xi: number; + xl: number; + yi: number; + yl: number; + } + + export interface Position { + left: number | string; + right: number | string; + top: number | string; + bottom: number | string; + } + + export interface Border { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; + /** + * Character to use if bg type, default is space. + */ + ch?: string; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + /** + * Border attributes. + */ + bold?: string; + underline?: string; + } + + export interface ElementOptions extends INodeOptions { + tags?: boolean; + + fg?: string; + bg?: string; + bold?: string; + underline?: string; + + style?: any; + /** + * Border object, see below. + */ + border?: Border | "line" | "bg"; + /** + * Element's text content. + */ + content?: string; + /** + * Element is clickable. + */ + clickable?: boolean; + /** + * Element is focusable and can receive key input. + */ + input?: boolean; + keyable?: boolean; + /** + * Element is focused. + */ + focused?: BlessedElement; + /** + * Whether the element is hidden. + */ + hidden?: boolean; + /** + * A simple text label for the element. + */ + label?: string; + /** + * A floating text label for the element which appears on mouseover. + */ + hoverText?: string; + /** + * Text alignment: left, center, or right. + */ + align?: "left" | "center" | "right"; + /** + * Vertical text alignment: top, middle, or bottom. + */ + valign?: "top" | "middle" | "bottom"; + /** + * Shrink/flex/grow to content and child elements. Width/height during render. + */ + shrink?: boolean; + /** + * Amount of padding on the inside of the element. Can be a number or an object containing + * the properties: left, right, top, and bottom. + */ + padding?: number | Padding; + + top?: Types.TTopLeft; + left?: Types.TTopLeft; + right?: Types.TPosition; + bottom?: Types.TPosition; + + /** + * Width/height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). + * Percentages can also have offsets (50%+1, 50%-1). + */ + width?: number | string; + /** + * Offsets of the element relative to its parent. Can be a number, percentage (0-100%), or + * keyword (center). right and bottom do not accept keywords. Percentages can also have + * offsets (50%+1, 50%-1). + */ + height?: number | string; + /** + * Can contain the above options. + */ + position?: Position; + /** + * Whether the element is scrollable or not. + */ + scrollable?: boolean; + /** + * Background character (default is whitespace ). + */ + ch?: string; + /** + * Allow the element to be dragged with the mouse. + */ + draggable?: boolean; + /** + * Draw a translucent offset shadow behind the element. + */ + shadow?: boolean; + } + + export interface Coords { + xl: number; + xi: number; + yl: number; + yi: number; + base: number; + _contentEnd: {x: number; y: number;}; + notop: Types.TTopLeft; + noleft: Types.TTopLeft; + noright: Types.TPosition; + nobot: Types.TPosition; + } + + export interface LabelOptions { + text: string; + side: Types.TAlign; + } + + // TODO: scrollable - Note: If the scrollable option is enabled, Element inherits all methods from ScrollableBox. + export abstract class BlessedElement extends NodeWithEvents implements IHasOptions { + constructor(opts: ElementOptions); + + // ** properties ** // + + /** + * Original options object. + */ + options: ElementOptions; + /** + * Name of the element. Useful for form submission. + */ + name: string; + /** + * Border object. + */ + border: Border; + + style: any; + position: Position; + content: string; + hidden: boolean; + visible: boolean; + detached: boolean; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg: number; + fg: number; + /** + * Border attributes. + */ + bold: string; + underline: string; + /** + * Calculated width. + */ + width: number | string; + /** + * Calculated height. + */ + height: number | string; + /** + * Calculated relative top offset.*/ + top: Types.TTopLeft; + /** + * Calculated relative left offset. + */ + left: Types.TTopLeft; + /** + * Calculated relative right offset. + */ + right: Types.TPosition; + /** + * Calculated relative bottom offset. + */ + bottom: Types.TPosition; + /** + * Calculated absolute top offset. + */ + atop: Types.TTopLeft; + /** + * Calculated absolute left offset. + */ + aleft: Types.TTopLeft; + /** + * Calculated absolute right offset. + */ + aright: Types.TPosition; + /** + * Calculated absolute bottom offset. + */ + abottom: Types.TPosition; + + /** + * Whether the element is draggable. Set to true to allow dragging. + */ + draggable: boolean; + + itop: Types.TTopLeft; + ileft: Types.TTopLeft; + iheight: Types.TPosition; + iwidth: Types.TPosition; + + /** + * Calculated relative top offset. + */ + rtop: Types.TTopLeft; + /** + * Calculated relative left offset. + */ + rleft: Types.TTopLeft; + /** + * Calculated relative right offset. + */ + rright: Types.TPosition; + /** + * Calculated relative bottom offset. + */ + rbottom: Types.TPosition; + + lpos: PositionCoords; + + // ** methods ** // + + /** + * Write content and children to the screen buffer. + */ + render(): Coords; + /** + * Hide element.*/ + hide(): void; + /** + * Show element. + */ + show(): void; + /** + * Toggle hidden/shown. + */ + toggle(): void; + /** + * Focus element. + */ + focus(): void; + /** + * Same asel.on('screen', ...) except this will automatically keep track of which listeners + * are bound to the screen object. For use with removeScreenEvent(), free(), and destroy(). + */ + onScreenEvent(type: string, handler: Function): void; + /** + * Same asel.removeListener('screen', ...) except this will automatically keep track of which + * listeners are bound to the screen object. For use with onScreenEvent(), free(), and destroy(). + */ + removeScreenEvent(type: string, handler: Function): void; + /** + * Free up the element. Automatically unbind all events that may have been bound to the screen + * object. This prevents memory leaks. For use with onScreenEvent(), removeScreenEvent(), + * and destroy(). + */ + free(): void; + /** + * Same as the detach() method, except this will automatically call free() and unbind any screen + * events to prevent memory leaks. for use with onScreenEvent(), removeScreenEvent(), and free(). + */ + destroy(): void; + /** + * Set the z-index of the element (changes rendering order). + */ + setIndex(z: number): void; + /** + * Put the element in front of its siblings.*/ + setFront(): void; + /** + * Put the element in back of its siblings. + */ + setBack(): void; + /** + * text/options - Set the label text for the top-left corner. Example options: {text:'foo',side:'left'} + */ + setLabel(arg: string | LabelOptions): void; + /** + * Remove the label completely. + */ + removeLabel(): any; + /** + * text/options - Set a hover text box to follow the cursor. Similar to the "title" DOM attribute + * in the browser. Example options: {text:'foo'} + */ + setHover(arg: string | LabelOptions): void; + /** + * Remove the hover label completely. + */ + removeHover(): void; + /** + * Enable mouse events for the element (automatically called when a form of on('mouse') is bound). + */ + enableMouse(): void; + /** + * Enable keypress events for the element (automatically called when a form of on('keypress') is bound). + */ + enableKeys(): void; + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(): void; + /** + * Enable dragging of the element. + */ + enableDrag(): void; + /** + * Disable dragging of the element. + */ + disableDrag(): void; + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + + /* + Content Methods + + Methods for dealing with text content, line by line. Useful for writing a text editor, + irc client, etc. + + Note: All of these methods deal with pre-aligned, pre-wrapped text. If you use deleteTop() + on a box with a wrapped line at the top, it may remove 3-4 "real" lines (rows) depending + on how long the original line was. + + The lines parameter can be a string or an array of strings. The line parameter must + be a string. + */ + + /** + * Set the content. Note: When text is input, it will be stripped of all non-SGR + * escape codes, tabs will be replaced with 8 spaces, and tags will be replaced + * with SGR codes (if enabled). + */ + setContent(text: string): void; + /** + * Return content, slightly different from el.content. Assume the above formatting. + */ + getContent(): string; + /** + * Similar to setContent, but ignore tags and remove escape codes. + */ + setText(text: string): void; + /** + * Similar to getContent, but return content with tags and escape codes removed. + */ + getText(): string; + /** + * Insert a line into the box's content. + */ + insertLine(i: number, lines: string | string[]): void; + /** + * Delete a line from the box's content. + */ + deleteLine(i: number): void; + /** + * Get a line from the box's content. + */ + getLine(i: number): string; + /** + * Get a line from the box's content from the visible top. + */ + getBaseLine(i: number): string; + /** + * Set a line in the box's content. + */ + setLine(i: number, line: string | string[]): void; + /** + * Set a line in the box's content from the visible top. + */ + setBaseLine(i: number, line: string | string[]): void; + /** + * Clear a line from the box's content. + */ + clearLine(i: number): void; + /** + * Clear a line from the box's content from the visible top. + */ + clearBaseLine(i: number): void; + /** + * Insert a line at the top of the box. + */ + insertTop(lines: string | string[]): void; + /** + * Insert a line at the bottom of the box. + */ + insertBottom(lines: string | string[]): void; + /** + * Delete a line at the top of the box. + */ + deleteTop(): void; + /** + * Delete a line at the bottom of the box. + */ + deleteBottom(): void; + /** + * Unshift a line onto the top of the content. + */ + unshiftLine(lines: string | string[]): void; + /** + * Shift a line off the top of the content. + */ + shiftLine(i: number): void; + /** + * Push a line onto the bottom of the content. + */ + pushLine(lines: string | string[]): void; + /** + * Pop a line off the bottom of the content. + */ + popLine(i: number): string; + /** + * An array containing the content lines. + */ + getLines(): string[]; + /** + * An array containing the lines as they are displayed on the screen. + */ + getScreenLines(): string[]; + /** + * Get a string's displayed width, taking into account double-width, surrogate pairs, + * combining characters, tags, and SGR escape codes. + */ + strWidth(text: string): string; + + // ** events ** // + } + + export interface ScrollableBoxOptions extends ElementOptions { + /** + * A limit to the childBase. Default is Infinity. + */ + baseLimit?: number; + /** + * A option which causes the ignoring of childOffset. This in turn causes the + * childBase to change every time the element is scrolled. + */ + alwaysScroll?: boolean; + /** + * Object enabling a scrollbar. + * Style of the scrollbar track if present (takes regular style options). + */ + scrollbar?: { style?: any; track?: any; ch?: string; } + } + + export interface ScrollableTextOptions extends ScrollableBoxOptions { + /** + * Whether to enable automatic mouse support for this element. + * Use pre-defined mouse events (right-click for editor). + */ + mouse?: boolean | (() => void); + /** + * Use pre-defined keys (i or enter for insert, e for editor, C-e for editor while inserting). + */ + keys?: string | string[] | boolean; + /** + * Use vi keys with the keys option. + */ + vi?: boolean; + } + + export interface BoxOptions extends ScrollableTextOptions { + bindings?: any; + } + + /** + * DEPRECATED - Use Box with the scrollable option instead. A box with scrollable content. + */ + export class ScrollableBoxElement extends BlessedElement { + /** + * The offset of the top of the scroll content. + */ + childBase: number; + /** + * The offset of the chosen item/line. + */ + childOffset: number; + + /** + * Scroll the content by a relative offset. + */ + scroll(offset: number, always?: boolean): void; + /** + * Scroll the content to an absolute index. + */ + scrollTo(index: number): void; + /** + * Same as scrollTo. + */ + setScroll(index: number): void; + /** + * Set the current scroll index in percentage (0-100). + */ + setScrollPerc(perc: number): void; + /** + * Get the current scroll index in lines. + */ + getScroll(): void; + /** + * Get the actual height of the scrolling area. + */ + getScrollHeight(): void; + /** + * Get the current scroll index in percentage. + */ + getScrollPerc(): void; + /** + * Reset the scroll index to its initial state. + */ + resetScroll(): void; + + on(event: string, listener: Function): this; + /** + * Received when the element is scrolled. + */ + on(event: "scroll", callback: () => void): this; + } + + /** + * DEPRECATED - Use Box with the scrollable and alwaysScroll options instead. + * A scrollable text box which can display and scroll text, as well as handle + * pre-existing newlines and escape codes. + */ + export class ScrollableTextElement extends ScrollableBoxElement { + } + + /** + * A box element which draws a simple box containing content or other elements. + */ + export class BoxElement extends ScrollableTextElement implements IHasOptions { + constructor(opts: BoxOptions); + + /** + * Original options object. + */ + options: BoxOptions; + } + + export interface TextOptions extends ElementOptions { + /** + * Fill the entire line with chosen bg until parent bg ends, even if there + * is not enough text to fill the entire width. + */ + fill?: boolean; + /** + * Text alignment: left, center, or right. + */ + align?: Types.TAlign; + } + + /** + * An element similar to Box, but geared towards rendering simple text elements. + */ + export class TextElement extends BlessedElement implements IHasOptions { + constructor(opts: TextOptions); + + /** + * Original options object. + */ + options: TextOptions; + } + + /** + * A simple line which can be line or bg styled. + */ + export interface LineOptions extends BoxOptions { + /** + * Can be vertical or horizontal. + */ + orientation?: "vertical" | "horizontal"; + /** + * Treated the same as a border object. (attributes can be contained in style). + */ + type?: string; + bg?: string; + fg?: string; + ch?: string; + } + + /** + * A simple line which can be line or bg styled. + */ + export class LineElement extends BoxElement implements IHasOptions { + constructor(opts: LineOptions); + + /** + * Original options object. + */ + options: LineOptions; + } + + export interface BigTextOptions extends BoxOptions { + /** + * bdf->json font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + font?: string; + /** + * bdf->json bold font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + fontBold?: string; + /** + * foreground character. (default: ' ') + */ + fch?: string; + } + + /** + * A box which can render content drawn as 8x14 cell characters using the terminus font. + */ + export class BigTextElement extends BoxElement implements IHasOptions { + constructor(opts: BigTextOptions); + + /** + * Original options object. + */ + options: BigTextOptions; + } + + export interface ListElementStyle { + selected?: any; + item?: any; + } + + export interface ListOptions extends BoxOptions { + /** + * Style for a selected item. Style for an unselected item. + */ + style?: TStyle; + /** + * An array of strings which become the list's items. + */ + items?: string[]; + /** + * A function that is called when vi mode is enabled and the key / is pressed. This function accepts a + * callback function which should be called with the search string. The search string is then used to + * jump to an item that is found in items. + */ + search?: () => void; + /** + * Whether the list is interactive and can have items selected (Default: true). + */ + interactive?: boolean; + /** + * Whether to automatically override tags and invert fg of item when selected (Default: true). + */ + invertSelected?: boolean; + } + + export class ListElement extends BoxElement implements IHasOptions> { + constructor(opts: ListOptions); + + /** + * Original options object. + */ + options: ListOptions; + + /** + * Add an item based on a string. + */ + add(text: string): void; + /** + * Add an item based on a string. + */ + addItem(text: string): void; + /** + * Removes an item from the list. Child can be an element, index, or string. + */ + removeItem(child: BlessedElement): BlessedElement; + /** + * Push an item onto the list. + * */ + pushItem(child: BlessedElement): number; + /** + * Pop an item off the list. + * */ + popItem(): BlessedElement; + /** + * Unshift an item onto the list. + */ + unshiftItem(child: BlessedElement): number; + /** + * Shift an item off the list. + * */ + shiftItem(): BlessedElement; + /** + * Inserts an item to the list. Child can be an element, index, or string. + */ + insertItem(i: number, child: BlessedElement): void; + /** + * Returns the item element. Child can be an element, index, or string. + */ + getItem(child: BlessedElement): BlessedElement; + /** + * Set item to content. + */ + setItem(child: BlessedElement, content: BlessedElement | string): void; + /** + * Remove and insert items to the list. + * */ + spliceItem(i: number, n: number, ...items: BlessedElement[]): void; + /** + * Clears all items from the list. + * */ + clearItems(): void; + /** + * Sets the list items to multiple strings. + */ + setItems(items: BlessedElement[]): void; + /** + * Returns the item index from the list. Child can be an element, index, or string. + */ + getItemIndex(child: BlessedElement): number; + /** + * Select an index of an item. + * */ + select(index: number): void; + /** + * Select item based on current offset. + * */ + move(offset: number): void; + /** + * Select item above selected. + * */ + up(amount: number): void; + /** + * Select item below selected. + */ + down(amount: number): void; + /** + * Show/focus list and pick an item. The callback is executed with the result. + */ + pick(callback: () => void): void; + /** + * Find an item based on its text content. + */ + fuzzyFind(arg: string | RegExp | (() => void)): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when an item is selected. + */ + on(event: "select", callback: (item: BoxElement, index: number) => void): this; + /** + * List was canceled (when esc is pressed with the keys option). + */ + on(event: "cancel", callback: () => void): this; + /** + * Either a select or a cancel event was received. + */ + on(event: "action", callback: () => void): this; + + on(event: "create item", callback: () => void): this; + on(event: "add item", callback: () => void): this; + on(event: "remove item", callback: () => void): this; + on(event: "insert item", callback: () => void): this; + on(event: "set items", callback: () => void): this; + on(event: "select item", callback: (item: BlessedElement, index: number) => void): this; + } + + export interface FileManagerOptions extends ListOptions { + /** + * Current working directory. + */ + cwd?: string; + } + + export class FileManagerElement extends ListElement implements IHasOptions { + constructor(opts: FileManagerOptions); + + /** + * Original options object. + */ + options: FileManagerOptions; + /** + * Current working directory. + */ + cwd: string; + + /** + * Refresh the file list (perform a readdir on cwd and update the list items). + */ + refresh(cwd:string, callback: () => void): void; + refresh(callback: () => void): void; + refresh(): void; + /** + * Pick a single file and return the path in the callback. + */ + pick(cwd:string, callback: () => void): void; + pick(callback: () => void): void; + /** + * Reset back to original cwd. + */ + reset(cwd:string, callback: () => void): void; + reset(callback: () => void): void; + reset(): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when an item is selected. + */ + on(event: "cd", callback: (file: string, cwd: string) => void): this; + /** + * Received when an item is selected. + */ + on(event: "file", callback: (file: string) => void): this; + + on(event: "error", callback: (err: any, file: string) => void): this; + on(event: "refresh", callback: () => void): this; + } + + export interface StyleListTable extends ListElementStyle { + /** + * Header style. + */ + header?: any; + /** + * Cell style. + */ + cell?: any; + } + + export interface ListTableOptions extends ListOptions { + /** + * Array of array of strings representing rows. + */ + rows?: string[]; + data?: string[][]; + /** + * Spaces to attempt to pad on the sides of each cell. 2 by default: one space on each side + * (only useful if the width is shrunken). + */ + pad?: number; + /** + * Do not draw inner cells. + */ + noCellBorders?: boolean; + + style?: StyleListTable; + } + + export class ListTableElement extends ListElement implements IHasOptions { + constructor(opts: ListTableOptions); + + /** + * Original options object. + */ + options: ListTableOptions; + + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + [ 'Animals', 'Foods' ], + [ 'Elephant', 'Apple' ], + [ 'Bird', 'Orange' ] + ]); + */ + setRows(rows: string[][]): void; + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + [ 'Animals', 'Foods' ], + [ 'Elephant', 'Apple' ], + [ 'Bird', 'Orange' ] + ]); + */ + setData(rows: string[][]): void; + } + + export interface ListbarOptions extends BoxOptions { + style?: ListElementStyle; + /** + * Set buttons using an object with keys as titles of buttons, containing of objects + * containing keys of keys and callback. + */ + commands: Types.ListbarCommand[]; + items: Types.ListbarCommand[]; + /** + * Automatically bind list buttons to keys 0-9. + */ + autoCommandKeys: boolean; + } + + export class ListbarElement extends BoxElement implements IHasOptions { + constructor(opts: ListbarOptions); + + /** + * Original options object. + */ + options: ListbarOptions; + + /** + * Set commands (see commands option above). + */ + setItems(commands: Types.ListbarCommand[]): void; + /** + * Append an item to the bar. + */ + add(item: Types.ListbarCommand, callback: () => void): void; + /** + * Append an item to the bar. + */ + addItem(item: Types.ListbarCommand, callback: () => void): void; + /** + * Append an item to the bar. + */ + appendItem(item: Types.ListbarCommand, callback: () => void): void; + /** + * Select an item on the bar. + */ + select(offset: number): void; + /** + * Remove item from the bar. + */ + removeItem(child: BlessedElement): void; + /** + * Move relatively across the bar. + */ + move(offset: number): void; + /** + * Move left relatively across the bar. + */ + moveLeft(offset: number): void; + /** + * Move right relatively across the bar. + */ + moveRight(offset: number): void; + /** + * Select button and execute its callback. + */ + selectTab(index: number): void; + + // ** events ** // + + on(event: string, listener: Function): this; + + on(event: "set items", callback: () => void): this; + on(event: "remove item", callback: () => void): this; + on(event: "select tab", callback: () => void): this; + } + + export interface FormOptions extends BoxOptions { + /** + * Allow default keys (tab, vi keys, enter). + */ + keys?: any; + /** + * Allow vi keys. + */ + vi?: boolean; + } + + export class FormElement extends BoxElement implements IHasOptions { + constructor(opts: FormOptions); + + /** + * Original options object. + */ + options: FormOptions; + /** + * Last submitted data. + */ + submission: TFormData; + + /** + * Focus next form element. + */ + focusNext(): void; + /** + * Focus previous form element. + */ + focusPrevious(): void; + /** + * Submit the form. + */ + submit(): void; + /** + * Discard the form. + */ + cancel(): void; + /** + * Clear the form. + */ + reset(): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Form is submitted. Receives a data object. + */ + on(event: "submit", callback: (out: TFormData) => void): this; + /** + * Form is discarded. + */ + on(event: "cancel", callback: () => void): this; + /** + * Form is cleared. + */ + on(event: "reset", callback: () => void): this; + } + + export interface InputOptions extends BoxOptions { } + + export abstract class InputElement extends BoxElement { + constructor(opts: InputOptions); + } + + /** + * A box which allows multiline text input. + */ + export interface TextareaOptions extends InputOptions { + /** + * Call readInput() when the element is focused. Automatically unfocus. + */ + inputOnFocus?: boolean; + } + + export class TextareaElement extends InputElement implements IHasOptions { + constructor(opts: TextareaOptions); + + /** + * Original options object. + */ + options: TextareaOptions; + + /** + * The input text. read-only. + */ + value: string; + + /** + * Submit the textarea (emits submit). + */ + submit(): void; + /** + * Cancel the textarea (emits cancel). + */ + cancel(): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + readInput(callback?: (err: any, value?: string) => void): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + input(callback: (err: any, value?: string) => void): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + setInput(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + readEditor(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + editor(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + setEditor(callback: (err: any, value?: string) => void): void; + /** + * The same as this.value, for now. + */ + getValue(): string; + /** + * Clear input. + */ + clearValue(): void; + /** + * Set value. + */ + setValue(text: string): void; + + // ** events ** // + + on(event: string, listener: Function): this; + + on(event: "error", callback: (err: any) => void): this; + + /** + * Value is submitted (enter). + */ + on(event: "submit", callback: (value: any) => void): this; + /** + * Value is discared (escape). + */ + on(event: "cancel", callback: (value: any) => void): this; + /** + * Either submit or cancel. + */ + on(event: "action", callback: (value: any) => void): this; + } + + export interface TextboxOptions extends TextareaOptions { + /** + * Completely hide text. + */ + secret?: boolean; + /** + * Replace text with asterisks (*). + */ + censor?: boolean; + } + + export class TextboxElement extends TextareaElement implements IHasOptions { + constructor(opts: TextboxOptions); + + /** + * Original options object. + */ + options: TextboxOptions; + + /** + * Completely hide text. + */ + secret: boolean; + /** + * Replace text with asterisks (*). + */ + censor: boolean; + } + + export interface ButtonOptions extends BoxOptions { } + + export class ButtonElement extends InputElement implements IHasOptions { + constructor(opts: ButtonOptions); + + /** + * Original options object. + */ + options: ButtonOptions; + + /** + * Press button. Emits press. + */ + press(): void; + + on(event: string, listener: Function): this; + + on(event: "press", callback: () => void): this; + } + + export interface CheckboxOptions extends BoxOptions { + /** + * whether the element is checked or not. + * */ + checked?: boolean; + /** + * enable mouse support. + * */ + mouse?: boolean; + } + + /** + * A checkbox which can be used in a form element. + * */ + export class CheckboxElement extends InputElement implements IHasOptions { + constructor(options?: CheckboxOptions); + + /** + * Original options object. + */ + options: CheckboxOptions; + + /** + * the text next to the checkbox (do not use setcontent, use `check.text = ''`). + * */ + text: string; + /** + * whether the element is checked or not. + * */ + checked: boolean; + /** + * same as `checked`. + * */ + value: boolean; + + /** + * check the element. + * */ + check(): void; + /** + * uncheck the element. + * */ + uncheck(): void; + /** + * toggle checked state. + * */ + toggle(): void; + } + + export interface RadioSetOptions extends BoxOptions { } + + /** + * An element wrapping RadioButtons. RadioButtons within this element will be mutually exclusive + * with each other. + * */ + export abstract class RadioSetElement extends BoxElement { + constructor(opts: RadioSetOptions); + } + + export interface RadioButtonOptions extends BoxOptions { } + + /** + * A radio button which can be used in a form element. + */ + export abstract class RadioButtonElement extends CheckboxElement { + constructor(opts: RadioButtonOptions); + } + + export interface PromptOptions extends BoxOptions { } + + /** + * A prompt box containing a text input, okay, and cancel buttons (automatically hidden). + */ + export class PromptElement extends BoxElement implements IHasOptions { + constructor(opts: PromptOptions); + + options: PromptOptions; + + /** + * Show the prompt and wait for the result of the textbox. Set text and initial value. + */ + input(text: string, value: string, callback: (err: any, value: string) => void): void; + setInput(text: string, value: string, callback: (err: any, value: string) => void): void; + readInput(text: string, value: string, callback: (err: any, value: string) => void): void; + } + + export interface QuestionOptions extends BoxOptions { } + + /** + * A question box containing okay and cancel buttons (automatically hidden). + */ + export class QuestionElement extends BoxElement implements IHasOptions { + constructor(opts: QuestionOptions); + + options: QuestionOptions; + + /** + * Ask a question. callback will yield the result. + */ + ask(question: string, callback: (err: any, value: string) => void): void; + } + + export interface MessageOptions extends BoxOptions { } + + /** + * A box containing a message to be displayed (automatically hidden). + */ + export class MessageElement extends BoxElement implements IHasOptions { + constructor(opts: MessageOptions); + + options: MessageOptions; + + /** + * Display a message for a time (default is 3 seconds). Set time to 0 for a perpetual message that is dismissed on keypress. + */ + log(text: string, time: number, callback: (err: any) => void): void; + log(text: string, callback: (err: any) => void): void; + display(text: string, time: number, callback: (err: any) => void): void; + display(text: string, callback: (err: any) => void): void; + + /** + * Display an error in the same way. + */ + error(text: string, time: number, callback: () => void): void; + error(text: string, callback: () => void): void; + } + + export interface LoadingOptions extends BoxOptions { } + + /** + * A box with a spinning line to denote loading (automatically hidden). + */ + export class LoadingElement extends BoxElement implements IHasOptions { + constructor(opts: LoadingOptions); + + options: LoadingOptions; + + /** + * Display the loading box with a message. Will lock keys until stop is called. + */ + load(text: string): void; + /** + * Hide loading box. Unlock keys. + */ + stop(): void; + } + + export interface ProgressBarOptions extends BoxOptions { + /** + * can be `horizontal` or `vertical`. + * */ + orientation: string; + /** + * the character to fill the bar with (default is space). + * */ + pch: string; + /** + * the amount filled (0 - 100). + * */ + filled: number; + /** + * same as `filled`. + * */ + value: number; + /** + * enable key support. + * */ + keys: boolean; + /** + * enable mouse support. + * */ + mouse: boolean; + } + + /** + * A progress bar allowing various styles. This can also be used as a form input. + */ + export class ProgressBarElement extends InputElement implements IHasOptions { + constructor(options?: ProgressBarOptions); + + options: ProgressBarOptions; + + /** + * progress the bar by a fill amount. + * */ + progress(amount:number): void; + /** + * set progress to specific amount. + * */ + setProgress(amount:number): void; + /** + * reset the bar. + * */ + reset(): void; + + on(event: string, listener: Function): this; + /** + * Bar was reset. + */ + on(event: "reset", callback: () => void): this; + /** + * Bar has completely filled. + */ + on(event: "complete", callback: () => void): this; + } + + export interface LogOptions extends ScrollableTextOptions { + /** + * amount of scrollback allowed. default: Infinity. + * */ + scrollback?: number; + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + * */ + scrollOnInput?: boolean; + } + + /** + * A log permanently scrolled to the bottom. + * */ + export class Log extends ScrollableTextElement implements IHasOptions { + constructor(options?: LogOptions); + + options: LogOptions; + + /** + * amount of scrollback allowed. default: Infinity. + * */ + scrollback: number; + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + * */ + scrollOnInput: boolean; + + /** + * add a log line. + * */ + log(text:string): void; + /** + * add a log line. + * */ + add(text:string): void; + } + + export interface TableOptions extends BoxOptions { + /** + * array of array of strings representing rows (same as `data`). + * */ + rows?: string[][]; + /** + * array of array of strings representing rows (same as `rows`). + * */ + data?: string[][]; + /** + * spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). + * */ + pad?: number; + /** + * do not draw inner cells. + * */ + noCellBorders?: boolean; + /** + * fill cell borders with the adjacent background color. + * */ + fillCellBorders?: boolean; + } + + /** + * A stylized table of text elements. + * */ + export class TableElement extends BoxElement implements IHasOptions { + constructor(opts: TableOptions); + + options: TableOptions; + + /** + * set rows in table. array of arrays of strings. + * */ + setData(rows: string[][]): void; + /** + * set rows in table. array of arrays of strings. + * */ + setRows(rows: string[][]): void; + } + + export interface TerminalOptions extends BoxOptions { + /** + * handler for input data. + * */ + handler?: (userInput:Buffer) => void; + /** + * name of shell. $SHELL by default. + * */ + shell?:string; + /** + * args for shell. + * */ + args?:any; + /** + * can be line, underline, and block. + * */ + cursor?: 'line'|'underline'|'block'; + + terminal?: string; + + /** + * Object for process env. + */ + env?: any; + } + + export class TerminalElement extends BoxElement implements IHasOptions { + constructor(opts: TerminalOptions); + + options: TerminalOptions; + + /** + * reference to the headless term.js terminal. + * */ + term: any; + /** + * reference to the pty.js pseudo terminal. + * */ + pty: any; + + /** + * write data to the terminal. + * */ + write(data:string): void; + + /** + * nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. + * */ + screenshot(xi?:number, xl?:number, yi?:number, yl?:number): string; + } + + export interface ImageOptions extends BoxOptions { + /** + * path to image. + * */ + file: string; + /** + * path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. + * */ + type: "ansi" | "overlay" | "w3m"; + } + + /** + * Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. + * */ + export class ImageElement extends BoxElement implements IHasOptions { + constructor(options?: ImageOptions); + + options: ImageOptions; + } + + export interface ANSIImageOptions extends BoxOptions { + /** + * URL or path to PNG/GIF file. Can also be a buffer. + * */ + file: string; + /** + * Scale cellmap down (0-1.0) from its original pixel width/height (Default: 1.0). + * */ + scale: number; + + /** + * This differs from other element's width or height in that only one of them is needed: blessed will maintain the aspect ratio of the image as it scales down to the proper number of cells. NOTE: PNG/GIF's are always automatically shrunken to size (based on scale) if a width or height is not given. + * */ + width: number | string; + height: number | string; + + /** + * Add various "density" ASCII characters over the rendering to give the image more detail, similar to libcaca/libcucul (the library mplayer uses to display videos in the terminal). + */ + ascii: string; + + /** + * Whether to animate if the image is an APNG/animating GIF. If false, only display the first frame or IDAT (Default: true). + */ + animate: boolean; + + /** + * Set the speed of animation. Slower: 0.0-1.0. Faster: 1-1000. It cannot go faster than 1 frame per millisecond, so 1000 is the fastest. (Default: 1.0) + */ + speed: number; + + /** + * mem or cpu. If optimizing for memory, animation frames will be rendered to bitmaps as the animation plays, using less memory. Optimizing for cpu will precompile all bitmaps beforehand, which may be faster, but might also OOM the process on large images. (Default: mem). + */ + optimization: "mem" | "cpu"; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + * */ + export class ANSIImageElement extends BoxElement implements IHasOptions { + constructor(options?:ANSIImageOptions); + + options: ANSIImageOptions; + + /** + * Image object from the png reader. + */ + img: Types.TImage; + + /** + * set the image in the box to a new path. + * */ + setImage(img: string, callback: () => void): void; + /** + * clear the current image. + * */ + clearImage(callback: () => void): void; + /** + * Play animation if it has been paused or stopped. + */ + play(): void; + /** + * Pause animation. + */ + pause(): void; + /** + * Stop animation. + */ + stop(): void; + } + + export interface OverlayImageOptions extends BoxOptions { + /** + * Path to image. + */ + file: string; + /** + * Render the file as ANSI art instead of using w3m to overlay Internally uses the ANSIImage element. See the ANSIImage element for more information/options. (Default: true). + */ + ansi: boolean; + /** + * Path to w3mimgdisplay. If a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. + */ + w3m: string; + /** + * Whether to search /usr, /bin, and /lib for w3mimgdisplay (Default: true). + */ + search: string; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + * */ + export class OverlayImageElement extends BoxElement implements IHasOptions { + constructor(options?: OverlayImageOptions); + + options: OverlayImageOptions; + + /** + * set the image in the box to a new path. + * */ + setImage(img: string, callback: () => void): void; + /** + * clear the current image. + * */ + clearImage(callback: () => void): void; + /** + * get the size of an image file in pixels. + * */ + imageSize(img:string, callback: () => void): void; + /** + * get the size of the terminal in pixels. + * */ + termSize(callback: () => void): void; + /** + * get the pixel to cell ratio for the terminal. + * */ + getPixelRatio(callback: () => void): void; + } + + export interface VideoOptions extends BoxOptions { + /** + * Video to play. + */ + file: string; + /** + * Start time in seconds. + */ + start: number; + } + + export class VideoElement extends BoxElement implements IHasOptions { + constructor(options?: VideoOptions); + + options: VideoOptions; + + /** + * The terminal element running mplayer or mpv. + */ + tty: any; + } + + export interface LayoutOptions extends ElementOptions { + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer?: () => void; + + /** + * Using the default renderer, it provides two layouts: inline, and grid. inline is the default and will render + * akin to inline-block. grid will create an automatic grid based on element dimensions. The grid cells' + * width and height are always determined by the largest children in the layout. + */ + layout: "inline" | "inline-block" | "grid"; + } + + export class LayoutElement extends BlessedElement implements IHasOptions { + constructor(options?: LayoutOptions); + + options: LayoutOptions; + + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer(coords: PositionCoords): void; + /** + * Check to see if a previous child element has been rendered and is visible on screen. This is only useful + * for checking child elements that have already been attempted to be rendered! see the example below. + */ + isRendered(el: BlessedElement): boolean; + /** + * Get the last rendered and visible child element based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. + */ + getLast(i: number): Element; + /** + * Get the last rendered and visible child element coords based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. See the example below. + */ + getLastCoords(i: number): PositionCoords; + } + + export class Program { + /** + Wrap the given text in terminal formatting codes corresponding to the given attribute + name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 + integer color number. + */ + text (text:string, attr:string): string; + } } - export = Blessed; + export module widget { + export class Element extends Widgets.BlessedElement { } + export class Node extends Widgets.Node { } + export class Screen extends Widgets.Screen { } + + export class Box extends Widgets.BoxElement { } + export class ScrollableBox extends Widgets.ScrollableBoxElement { } + export class ScrollableText extends Widgets.ScrollableTextElement { } + export class Text extends Widgets.BoxElement { } + export class Line extends Widgets.LineElement { } + export class BigText extends Widgets.BigTextElement { } + export class List extends Widgets.ListElement { } + export class FileManager extends Widgets.FileManagerElement { } + export class ListTable extends Widgets.ListTableElement { } + export class ListBar extends Widgets.ListbarElement { } + export class Form extends Widgets.FormElement { } + export class Textarea extends Widgets.TextareaElement { } + export class Button extends Widgets.ButtonElement { } + export class Checkbox extends Widgets.CheckboxElement { } + export class RadioSet extends Widgets.RadioSetElement { } + export class RadioButton extends Widgets.RadioButtonElement { } + + export class Prompt extends Widgets.PromptElement { } + export class question extends Widgets.QuestionElement { } + export class Message extends Widgets.MessageElement { } + export class Loading extends Widgets.LoadingElement { } + + export class ProgressBar extends Widgets.ProgressBarElement { } + export class Terminal extends Widgets.TerminalElement { } + } + + export function screen(options?: Widgets.IScreenOptions): Widgets.Screen; + + export function box(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function text(options?: Widgets.TextOptions): Widgets.TextElement; + export function line(options?: Widgets.LineOptions): Widgets.LineElement; + export function scrollablebox(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function scrollabletext(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function bigtext(options?: Widgets.BigTextOptions): Widgets.BigTextElement; + export function list(options?: Widgets.ListOptions): Widgets.ListElement; + export function filemanager(options?: Widgets.FileManagerOptions): Widgets.FileManagerElement; + export function listtable(options?: Widgets.ListTableOptions): Widgets.ListTableElement; + export function listbar(options?: Widgets.ListbarOptions): Widgets.ListbarElement; + export function form(options?: Widgets.FormOptions): Widgets.FormElement; + export function input(options?: Widgets.InputOptions): Widgets.InputElement; + export function textarea(options?: Widgets.TextareaOptions): Widgets.TextareaElement; + export function textbox(options?: Widgets.TextboxOptions): Widgets.TextboxElement; + export function button(options?: Widgets.ButtonOptions): Widgets.ButtonElement; + export function checkbox(options?: Widgets.CheckboxOptions): Widgets.CheckboxElement; + export function radioset(options?: Widgets.RadioSetOptions): Widgets.RadioSetElement; + export function radiobutton(options?: Widgets.RadioButtonOptions): Widgets.RadioButtonElement; + + export function table(options?: Widgets.TableOptions): Widgets.TableElement; + + export function prompt(options?: Widgets.PromptOptions): Widgets.PromptElement; + export function question(options?: Widgets.QuestionOptions): Widgets.QuestionElement; + export function message(options?: Widgets.MessageOptions): Widgets.MessageElement; + export function loading(options?: Widgets.LoadingOptions): Widgets.LoadingElement; + + export function progressbar(options?: Widgets.ProgressBarOptions): Widgets.ProgressBarElement; + export function terminal(options?: Widgets.TerminalOptions): Widgets.TerminalElement; + + export function layout(options?: Widgets.LayoutOptions): Widgets.LayoutElement; + + export function escape(item: any): any; + export const colors: { + match: (hexColor: string) => string + } } - - - From 0336e9c74991129516aa9a19ba937ae5938db694 Mon Sep 17 00:00:00 2001 From: Steve Lam Date: Sun, 7 Aug 2016 16:15:40 -0700 Subject: [PATCH 020/844] added type def for scriptjs https://github.com/ded/script.js --- scriptjs/scriptjs.d.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 scriptjs/scriptjs.d.ts diff --git a/scriptjs/scriptjs.d.ts b/scriptjs/scriptjs.d.ts new file mode 100644 index 0000000000..074633fc8f --- /dev/null +++ b/scriptjs/scriptjs.d.ts @@ -0,0 +1,12 @@ +interface $script { + (paths:string | string[], idOrDone:string | (() => void), optDone?:() => void): $script; + get(path:string, fn:() => void); + order(scripts:string[], id:string, done:() => void); + path(p:string); + urlArts(str:string); + ready(deps:string | string[], ready:() => void, req?:(missing:string[]) => void): $script; +} + +declare var $script: $script; + +export = $script; From e73fdc130f4594e7af6cc5e39389cd2dd1aae649 Mon Sep 17 00:00:00 2001 From: Steve Lam Date: Sun, 7 Aug 2016 16:33:32 -0700 Subject: [PATCH 021/844] fixed implicit return types --- scriptjs/scriptjs.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scriptjs/scriptjs.d.ts b/scriptjs/scriptjs.d.ts index 074633fc8f..b11e7d375a 100644 --- a/scriptjs/scriptjs.d.ts +++ b/scriptjs/scriptjs.d.ts @@ -1,9 +1,9 @@ interface $script { (paths:string | string[], idOrDone:string | (() => void), optDone?:() => void): $script; - get(path:string, fn:() => void); - order(scripts:string[], id:string, done:() => void); - path(p:string); - urlArts(str:string); + get(path:string, fn:() => void): void; + order(scripts:string[], id:string, done:() => void): void; + path(p:string): void; + urlArts(str:string): void; ready(deps:string | string[], ready:() => void, req?:(missing:string[]) => void): $script; } From 57b7904945e87dc732d5691a60ec90214aba83f4 Mon Sep 17 00:00:00 2001 From: Steve Lam Date: Sun, 7 Aug 2016 16:47:24 -0700 Subject: [PATCH 022/844] typo --- scriptjs/scriptjs.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scriptjs/scriptjs.d.ts b/scriptjs/scriptjs.d.ts index b11e7d375a..fd3ea76ab3 100644 --- a/scriptjs/scriptjs.d.ts +++ b/scriptjs/scriptjs.d.ts @@ -3,7 +3,7 @@ interface $script { get(path:string, fn:() => void): void; order(scripts:string[], id:string, done:() => void): void; path(p:string): void; - urlArts(str:string): void; + urlArgs(str:string): void; ready(deps:string | string[], ready:() => void, req?:(missing:string[]) => void): $script; } From 9dfc17e21bcd8a7356085cf5a3c3f2946b138b3c Mon Sep 17 00:00:00 2001 From: Steve Lam Date: Sun, 7 Aug 2016 16:47:53 -0700 Subject: [PATCH 023/844] added scriptjs tests --- scriptjs/scriptjs-tests.ts | 39 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 scriptjs/scriptjs-tests.ts diff --git a/scriptjs/scriptjs-tests.ts b/scriptjs/scriptjs-tests.ts new file mode 100644 index 0000000000..be7f393b4d --- /dev/null +++ b/scriptjs/scriptjs-tests.ts @@ -0,0 +1,39 @@ +/// + +import $script = require("scriptjs"); + +const callback = () => console.log('done'); + +function main(): void { + $script('foo.js', callback); + $script(['foo.js', 'bar.js'], callback); + + $script('foo.js', 'foo', callback); + $script(['foo.js', 'bar.js'], 'bundle', callback); + + $script('foo', callback); + $script('bundle', callback); + + $script.ready('foo', callback); + $script.ready('bundle', callback); + + const deps = { + foo: 'foo.js', + bar: 'bar.js', + thunk: ['thunkor.js', 'thunky.js'], + }; + + $script.ready(['foo', 'bar', 'thunk'], callback, (missing: string[]) => { + missing.forEach((dep: string) => { + $script(deps[dep], dep); + }); + }); + + $script.path('/js/modules/'); + + $script.get('http://example.com/base.js', callback); + + $script.urlArgs('key=value&foo=bar'); + + $script.order(['foo.js', 'bar.js'], 'bundle', callback); +} From 45ff6e7ac743f962556d02bfc1b6de90ac1a0369 Mon Sep 17 00:00:00 2001 From: Steve Lam Date: Sun, 7 Aug 2016 16:55:35 -0700 Subject: [PATCH 024/844] added meta data --- scriptjs/scriptjs.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/scriptjs/scriptjs.d.ts b/scriptjs/scriptjs.d.ts index fd3ea76ab3..7dd1ad304b 100644 --- a/scriptjs/scriptjs.d.ts +++ b/scriptjs/scriptjs.d.ts @@ -1,3 +1,8 @@ +// Type definitions for scriptjs +// Project: https://github.com/ded/script.js +// Definitions by: ssttevee +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + interface $script { (paths:string | string[], idOrDone:string | (() => void), optDone?:() => void): $script; get(path:string, fn:() => void): void; From bc62f69d28ad8729f0e1c3e798f82303d493e6e7 Mon Sep 17 00:00:00 2001 From: Steve Lam Date: Sun, 7 Aug 2016 16:57:23 -0700 Subject: [PATCH 025/844] explicit return type --- scriptjs/scriptjs-tests.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scriptjs/scriptjs-tests.ts b/scriptjs/scriptjs-tests.ts index be7f393b4d..027298891e 100644 --- a/scriptjs/scriptjs-tests.ts +++ b/scriptjs/scriptjs-tests.ts @@ -2,7 +2,7 @@ import $script = require("scriptjs"); -const callback = () => console.log('done'); +const callback = (): void => console.log('done'); function main(): void { $script('foo.js', callback); @@ -23,8 +23,8 @@ function main(): void { thunk: ['thunkor.js', 'thunky.js'], }; - $script.ready(['foo', 'bar', 'thunk'], callback, (missing: string[]) => { - missing.forEach((dep: string) => { + $script.ready(['foo', 'bar', 'thunk'], callback, (missing: string[]): void => { + missing.forEach((dep: string): void => { $script(deps[dep], dep); }); }); From 121f3f13452775c6f4aa651ecaba124c13334c7c Mon Sep 17 00:00:00 2001 From: Steve Lam Date: Sun, 7 Aug 2016 17:02:42 -0700 Subject: [PATCH 026/844] Update scriptjs.d.ts --- scriptjs/scriptjs.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scriptjs/scriptjs.d.ts b/scriptjs/scriptjs.d.ts index 7dd1ad304b..c0bf3d0c6d 100644 --- a/scriptjs/scriptjs.d.ts +++ b/scriptjs/scriptjs.d.ts @@ -1,6 +1,6 @@ // Type definitions for scriptjs // Project: https://github.com/ded/script.js -// Definitions by: ssttevee +// Definitions by: Steve Lam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface $script { From 251049a5e9b0a7fca462ea8abbc0a42c4031a582 Mon Sep 17 00:00:00 2001 From: Steve Lam Date: Sun, 7 Aug 2016 17:04:58 -0700 Subject: [PATCH 027/844] changed import statement --- scriptjs/scriptjs-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scriptjs/scriptjs-tests.ts b/scriptjs/scriptjs-tests.ts index 027298891e..3dbcbea3ac 100644 --- a/scriptjs/scriptjs-tests.ts +++ b/scriptjs/scriptjs-tests.ts @@ -1,6 +1,6 @@ /// -import $script = require("scriptjs"); +import * as $script from 'scriptjs'; const callback = (): void => console.log('done'); From afd81057b25c9c6931ea909d05829bb4035bfe4a Mon Sep 17 00:00:00 2001 From: Steve Lam Date: Sun, 7 Aug 2016 17:09:42 -0700 Subject: [PATCH 028/844] Update scriptjs-tests.ts --- scriptjs/scriptjs-tests.ts | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/scriptjs/scriptjs-tests.ts b/scriptjs/scriptjs-tests.ts index 3dbcbea3ac..4da747c978 100644 --- a/scriptjs/scriptjs-tests.ts +++ b/scriptjs/scriptjs-tests.ts @@ -17,17 +17,7 @@ function main(): void { $script.ready('foo', callback); $script.ready('bundle', callback); - const deps = { - foo: 'foo.js', - bar: 'bar.js', - thunk: ['thunkor.js', 'thunky.js'], - }; - - $script.ready(['foo', 'bar', 'thunk'], callback, (missing: string[]): void => { - missing.forEach((dep: string): void => { - $script(deps[dep], dep); - }); - }); + $script.ready(['foo', 'bar', 'thunk'], callback, (missing: string[]): void => console.log('missing deps:', missing)); $script.path('/js/modules/'); From 3e18cac5fc60ccb0091bce3115e64890865253d9 Mon Sep 17 00:00:00 2001 From: Garth Kidd Date: Wed, 10 Aug 2016 10:28:40 +1000 Subject: [PATCH 029/844] Add new type definition for xmlpoke --- xmlpoke/xmlpoke-tests.ts | 83 ++++++++++++++++++++++++++++++++++++++++ xmlpoke/xmlpoke.d.ts | 45 ++++++++++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 xmlpoke/xmlpoke-tests.ts create mode 100644 xmlpoke/xmlpoke.d.ts diff --git a/xmlpoke/xmlpoke-tests.ts b/xmlpoke/xmlpoke-tests.ts new file mode 100644 index 0000000000..b77463f164 --- /dev/null +++ b/xmlpoke/xmlpoke-tests.ts @@ -0,0 +1,83 @@ +/// +/// + +// tsc xmlpoke-tests.ts && node xmlpoke-tests.js + +import * as xmlpoke from 'xmlpoke'; +import * as assert from 'assert'; + +let result: string; + +// add with xpath, value +result = xmlpoke('', xml => xml.add('/a/b', 'c')); +assert.equal(result, 'c'); + +// add with xpath, Transform +const addfn: XmlPoke.Transform = (node, value) => 'c'; +result = xmlpoke('', xml => xml.add('/a/b', addfn)); +assert.equal(result, 'c'); + +// add with xpath, CDataValue +const cdataval: XmlPoke.CDataValue = new xmlpoke.CDataValue('c'); +result = xmlpoke('', xml => xml.add('/a/b', cdataval)); +assert.equal(result, ''); + +// add with xpath, XMLVal +const xmlval = new xmlpoke.XmlString(''); +result = xmlpoke('', xml => xml.add('/a/b', xmlval)); +assert.equal(result, ''); + +// add with map +result = xmlpoke('', xml => xml.add({ + '/a/b': 'c' +})); +assert.equal(result, 'c'); + +// set with xpath, value +result = xmlpoke('b', xml => xml.set('/a', 'c')); +assert.equal(result, 'c'); + +// set with map +result = xmlpoke('b', xml => xml.set({ + '/a': 'c' +})); +assert.equal(result, 'c'); + +// set with xpath that doesn't exist (no-op) +result = xmlpoke('bval', xml => xml.set('/a/c', 'cval')); +assert.equal(result, 'bval'); + +// setOrAdd with xpath, value +result = xmlpoke('', xml => xml.setOrAdd('/a/b', 'c')); +assert.equal(result, 'c'); + +// setOrAdd with map +result = xmlpoke('', xml => xml.setOrAdd({ + '/a/b': 'c' +})); +assert.equal(result, 'c'); + +// setOrAdd with xpath that doesn't exist: add +result = xmlpoke('bval', xml => xml.setOrAdd('/a/c', 'cval')); +assert.equal(result, 'bvalcval'); + +// remove +result = xmlpoke('', xml => xml.remove('//b')); +assert.equal(result, ''); + +// clear +result = xmlpoke('', xml => xml.clear('/a')); +assert.equal(result, ''); + +// withBasePath, addNamespace, errorOnNoMatches +result = xmlpoke('', xml => + xml.withBasePath('/test') + .addNamespace('x', 'http://example.com/x') + .errorOnNoMatches() + .set('/x', (node, value) => { + assert.equal(typeof node, 'object'); + assert.equal((node.constructor as any).name, 'Element'); + assert.equal(value, 'hello'); + return 'y'; + })); +assert.equal(result, 'y'); diff --git a/xmlpoke/xmlpoke.d.ts b/xmlpoke/xmlpoke.d.ts new file mode 100644 index 0000000000..4b8868be98 --- /dev/null +++ b/xmlpoke/xmlpoke.d.ts @@ -0,0 +1,45 @@ +// Type definitions for xmlpoke 0.1.12 +// Project: https://github.com/mikeobrien/node-xmlpoke +// Definitions by: Garth Kidd +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module XmlPoke { // ghost module + interface Transform { + (node: Node, value: string): Value; + } + type Value = string | boolean | number | XmlValue | CDataValue | PathToValueMap | Transform; + type PathToValueMap = { + [xpath: string]: Value; + } + interface API { + add(xpath: string, value: Value): API; + add(map: PathToValueMap): API; + set(xpath: string, value: Value): API; + set(map: PathToValueMap): API; + setOrAdd(xpath: string, value: Value): API; + setOrAdd(map: PathToValueMap): API; + remove(xpath: string): API; + clear(xpath: string): API; + withBasePath(xpath: string): API; + addNamespace(prefix: string, uri: string): API; + errorOnNoMatches(): API; + } + interface CDataValue { + value: string; + } + interface XmlValue { + value: string; + } +} + +declare module 'xmlpoke' { + const xmlpoke: { + (xml: string, modify: (api: XmlPoke.API) => void): string; + CDataValue: new (value: string) => XmlPoke.CDataValue; + XmlString: new (value: string) => XmlPoke.XmlValue; + }; + namespace xmlpoke {} + export = xmlpoke; +} From 0ebac1ef817e65b965d67b1255df7283f46d4001 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Thu, 11 Aug 2016 16:35:40 +0900 Subject: [PATCH 030/844] TypeScript-STL & Samchon Framework --- samchon-framework/samchon-framework.d.ts | 4554 +++++++++++++++++----- typescript-stl/typescript-stl-tests.ts | 2 +- typescript-stl/typescript-stl.d.ts | 1357 +++---- 3 files changed, 4371 insertions(+), 1542 deletions(-) diff --git a/samchon-framework/samchon-framework.d.ts b/samchon-framework/samchon-framework.d.ts index c81a9d1e5b..a6d03758dd 100644 --- a/samchon-framework/samchon-framework.d.ts +++ b/samchon-framework/samchon-framework.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Samchon Framework v1.2.0 +// Type definitions for Samchon Framework v2.0.0-beta.1 // Project: https://github.com/samchon/framework // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -11,28 +11,59 @@ declare module "samchon-framework" } /** - * Samchon Framework, A SDN framework. + *

Samchon-Framework

* + *

+ *

+ * + *

Samchon, a SDN (Software Defined Network) framework.

+ * + *

With Samchon Framework, you can implement distributed processing system within framework of OOD like + * handling S/W objects (classes). You can realize cloud and distributed system very easily with provided + * system templates and even integration with C++ is possible.

+ * + *

The goal, ultimate utilization model of Samchon Framework is, building cloud system with NodeJS and + * takING heavy works to C++ distributed systems with provided modules (those are system templates).

+ * + * @git https://github.com/samchon/framework * @author Jeongho Nam */ declare namespace samchon { -} -declare namespace samchon.library { -} -declare namespace samchon.collection { -} -declare namespace samchon.protocol { -} -declare namespace samchon.protocol.service { -} -declare namespace samchon.protocol.master { -} -declare namespace samchon.protocol.slave { + /** + *

Running on Node.

+ * + *

Test whether the JavaScript is running on Node.

+ * + * @references http://stackoverflow.com/questions/17575790/environment-detection-node-js-or-browser + */ + function is_node(): boolean; } declare namespace samchon.collection { /** * A {@link Vector} who can detect element I/O events. * + *
    + *
  • insert typed events:
      + *
    • {@link assign}
    • + *
    • {@link insert}
    • + *
    • {@link push}
    • + *
    • {@link push_back}
    • + *
    • {@link unshift}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link assign}
    • + *
    • {@link clear}
    • + *
    • {@link erase}
    • + *
    • {@link pop_back}
    • + *
    • {@link shift}
    • + *
    • {@link pop}
    • + *
    • {@link splice}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link sort}
    • + *
  • + *
+ * * @author Jeongho Nam */ class ArrayCollection extends std.Vector implements ICollection { @@ -80,38 +111,46 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.VectorIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.VectorIterator, last: std.VectorIterator): void; /** * @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; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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: "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; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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; /** * @inheritdoc */ @@ -132,12 +171,9 @@ declare namespace samchon.collection { } declare namespace samchon.library { /** - * An event class. - * - *
    - *
  • Comments from - https://developer.mozilla.org/en-US/docs/Web/API/Event/
  • - *
+ * A basic event class of Samchon Framework. * + * @reference https://developer.mozilla.org/en-US/docs/Web/API/Event * @author Jeongho Nam */ class BasicEvent implements Event { @@ -231,51 +267,78 @@ declare namespace samchon.library { } declare namespace samchon.collection { /** - * Type of function pointer for {@link CollectionEvent CollectionEvents}. + * Type of function pointer for listener of {@link CollectionEvent CollectionEvents}. */ interface CollectionEventListener extends EventListener { (event: CollectionEvent): void; } +} +declare namespace samchon.collection { /** - * + * @author Jeongho Nam */ class CollectionEvent extends library.BasicEvent { - static INSERT: string; - static ERASE: string; /** - * + * @hidden */ private first_; /** - * + * @hidden */ private last_; /** + * Initialization Constructor. * - * - * @param type + * @param type Type of collection event. * @param first * @param last */ constructor(type: string, first: std.Iterator, last: std.Iterator); + constructor(type: "insert", first: std.Iterator, last: std.Iterator); + constructor(type: "erase", first: std.Iterator, last: std.Iterator); + constructor(type: "refresh", first: std.Iterator, last: std.Iterator); /** - * + * Get associative container. */ container: ICollection; /** - * + * Get range of the first. */ first: std.Iterator; /** - * + * Get range of the last. */ last: std.Iterator; } } +declare namespace samchon.collection.CollectionEvent { + const INSERT: string; + const ERASE: string; + const REFRESH: string; +} declare namespace samchon.collection { /** * A {@link Deque} who can detect element I/O events. * + *

Below are list of methods who are dispatching {@link CollectionEvent}:

+ * + *
    + *
  • insert typed events:
      + *
    • {@link assign}
    • + *
    • {@link insert}
    • + *
    • {@link push}
    • + *
    • {@link push_front}
    • + *
    • {@link push_back}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link assign}
    • + *
    • {@link clear}
    • + *
    • {@link erase}
    • + *
    • {@link pop_front}
    • + *
    • {@link pop_back}
    • + *
  • + *
+ * * @author Jeongho Nam */ class DequeCollection extends std.Deque implements ICollection { @@ -323,44 +386,72 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.DequeIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.DequeIterator, last: std.DequeIterator): void; /** * @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; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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: "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; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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 { /** * A {@link HashMap} who can detect element I/O events. * + *
    + *
  • insert typed events:
      + *
    • {@link assign}
    • + *
    • {@link insert}
    • + *
    • {@link push}
    • + *
    • {@link set}
    • + *
    • {@link insert_or_assign}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link assign}
    • + *
    • {@link clear}
    • + *
    • {@link erase}
    • + *
    • {@link extract}
    • + *
  • + *
  • refresh typed events:
      + *
    • {@link set}
    • + *
    • {@link insert_or_assign}
    • + *
  • + *
+ * * @author Jeongho Nam */ class HashMapCollection extends std.HashMap implements ICollection> { @@ -384,42 +475,65 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; /** * @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; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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: "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; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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 { /** * A {@link HashMultiMap} who can detect element I/O events. * + *
    + *
  • insert typed events:
      + *
    • {@link assign}
    • + *
    • {@link insert}
    • + *
    • {@link push}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link assign}
    • + *
    • {@link clear}
    • + *
    • {@link erase}
    • + *
  • + *
+ * * @author Jeongho Nam */ class HashMultiMapCollection extends std.HashMap implements ICollection> { @@ -443,47 +557,143 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; /** * @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; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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: "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: "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 { + /** + * A {@link HashMultiSet} who can detect element I/O events. + * + *
    + *
  • insert typed events:
      + *
    • {@link assign}
    • + *
    • {@link insert}
    • + *
    • {@link push}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link assign}
    • + *
    • {@link clear}
    • + *
    • {@link erase}
    • + *
  • + *
+ * + * @author Jeongho Nam + */ + class HashMultiSetCollection extends std.HashMultiSet implements ICollection { + /** + * A chain object taking responsibility of dispatching events. + */ + private event_dispatcher_; /** * @inheritdoc */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + hasEventListener(type: string): boolean; /** * @inheritdoc */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @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; + /** + * @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; + /** + * @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; + /** + * @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; } } declare namespace samchon.collection { /** * A {@link HashSet} who can detect element I/O events. * + *
    + *
  • insert typed events:
      + *
    • {@link assign}
    • + *
    • {@link insert}
    • + *
    • {@link push}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link assign}
    • + *
    • {@link clear}
    • + *
    • {@link erase}
    • + *
    • {@link extract}
    • + *
  • + *
+ * * @author Jeongho Nam */ - class HashSetCollection extends std.TreeSet implements ICollection { + class HashSetCollection extends std.HashSet implements ICollection { /** * A chain object taking responsibility of dispatching events. */ @@ -507,216 +717,175 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + refresh(): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + refresh(it: std.SetIterator): void; /** * @inheritdoc */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: EventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; - } - class HashMultiSetCollection extends std.TreeMultiSet implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: Event): boolean; + refresh(first: std.SetIterator, last: std.SetIterator): void; /** * @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; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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: "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; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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 { /** * An interface for {@link IContainer containers} who can detect element I/O events. * + *

Below are list of methods who are dispatching {@link CollectionEvent}:

+ * + *
    + *
  • insert typed events:
      + *
    • {@link assign}
    • + *
    • {@link insert}
    • + *
    • {@link push}
    • + *
  • + *
  • erase typed events:
      + *
    • {@link assign}
    • + *
    • {@link clear}
    • + *
    • {@link erase}
    • + *
  • + * * @author Jeongho Nam */ interface ICollection extends std.base.IContainer, library.IEventDispatcher { + /** + *

    Dispatch a {@link CollectionEvent} with refresh typed.

    + * + *

    {@link ICollection} dispatches {@link CollectionEvent} typed insert or erase whenever + * elements I/O has occured. However, unlike those elements I/O events, content change in element level can't be + * detected. There's no way to detect those events automatically by {@link IContainer}.

    + * + *

    If you want to dispatch those typed events (notifying change on contents in element level), you've to + * dispatch refresh typed event manually, by yourself. Call {@link refresh refresh()} with specified + * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with + * refresh typed will be dispatched.

    + * + *

    If you don't specify any iterator, then the range of the refresh event will be all elements in this + * {@link ICollection collection}; {@link begin begin()} to {@link end end()}.

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

    Dispatch a {@link CollectionEvent} with refresh typed.

    + * + *

    {@link ICollection} dispatches {@link CollectionEvent} typed insert or erase whenever + * elements I/O has occured. However, unlike those elements I/O events, content change in element level can't be + * detected. There's no way to detect those events automatically by {@link IContainer}.

    + * + *

    If you want to dispatch those typed events (notifying change on contents in element level), you've to + * dispatch refresh typed event manually, by yourself. Call {@link refresh refresh()} with specified + * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with + * refresh typed will be dispatched.

    + * + * @param it An iterator targeting the content changed element. + */ + refresh(it: std.Iterator): void; + /** + *

    Dispatch a {@link CollectionEvent} with refresh typed.

    + * + *

    {@link ICollection} dispatches {@link CollectionEvent} typed insert or erase whenever + * elements I/O has occured. However, unlike those elements I/O events, content change in element level can't be + * detected. There's no way to detect those events automatically by {@link IContainer}.

    + * + *

    If you want to dispatch those typed events (notifying change on contents in element level), you've to + * dispatch refresh typed event manually, by yourself. Call {@link refresh refresh()} with specified + * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with + * refresh typed will be dispatched.

    + * + * @param first An Iterator to the initial position in a sequence of the content changed elmeents. + * @param last An {@link Iterator} to the final position in a sequence of the content changed elements. The range + * used is [first, last), which contains all the elements between first and + * last, including the element pointed by first but not the element pointed by + * last. + */ + refresh(first: std.Iterator, last: std.Iterator): void; /** * @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; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): 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 - * list for a specific type of event, phase, and priority. - * - *

    After you successfully register an event listener, you cannot change its priority through - * additional calls to addEventListener(). To change a listener's priority, you must first call - * removeEventListener(). Then you can register the listener again with the new priority level.

    - * - *

    Keep in mind that after the listener is registered, subsequent calls to addEventListener() - * with a different type or useCapture value result in the creation of a separate listener - * registration. For example, if you first register a listener with useCapture set to true, - * it listens only during the capture phase. If you call addEventListener() again using the same - * listener object, but with useCapture set to false, you have two separate listeners: one that - * listens during the capture phase and another that listens during the target and bubbling phases.

    - * - *

    You cannot register an event listener for only the target phase or the bubbling phase. - * Those phases are coupled during registration because bubbling applies only to the ancestors of - * the target node.

    - * - *

    If you no longer need an event listener, remove it by calling removeEventListener(), or - * memory problems could result. Event listeners are not automatically removed from memory because - * the garbage collector does not remove the listener as long as the dispatching object exists - * (unless the useWeakReference parameter is set to true).

    - * - *

    Copying an EventDispatcher instance does not copy the event listeners attached to it. (If - * your newly created node needs an event listener, you must attach the listener after creating - * the node.) However, if you move an EventDispatcher instance, the event listeners attached to - * it move along with it.

    - * - *

    If the event listener is being registered on a node while an event is also being processed - * on this node, the event listener is not triggered during the current phase but may be triggered - * during a later phase in the event flow, such as the bubbling phase.

    - * - *

    If an event listener is removed from a node while an event is being processed on the node, - * it is still triggered by the current actions. After it is removed, the event listener is never - * invoked again (unless it is registered again for future processing).

    - * - * @param event The type of event; {@link CollectionEvent.INSERT} or {@link CollectionEvent.ERASE}. - * @param listener The listener function that processes the event. - * This function must accept an Event object as its only parameter and must return - * nothing. - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): 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 - * list for a specific type of event, phase, and priority. - * - *

    After you successfully register an event listener, you cannot change its priority through - * additional calls to addEventListener(). To change a listener's priority, you must first call - * removeEventListener(). Then you can register the listener again with the new priority level.

    - * - *

    Keep in mind that after the listener is registered, subsequent calls to addEventListener() - * with a different type or useCapture value result in the creation of a separate listener - * registration. For example, if you first register a listener with useCapture set to true, - * it listens only during the capture phase. If you call addEventListener() again using the same - * listener object, but with useCapture set to false, you have two separate listeners: one that - * listens during the capture phase and another that listens during the target and bubbling phases.

    - * - *

    You cannot register an event listener for only the target phase or the bubbling phase. - * Those phases are coupled during registration because bubbling applies only to the ancestors of - * the target node.

    - * - *

    If you no longer need an event listener, remove it by calling removeEventListener(), or - * memory problems could result. Event listeners are not automatically removed from memory because - * the garbage collector does not remove the listener as long as the dispatching object exists - * (unless the useWeakReference parameter is set to true).

    - * - *

    Copying an EventDispatcher instance does not copy the event listeners attached to it. (If - * your newly created node needs an event listener, you must attach the listener after creating - * the node.) However, if you move an EventDispatcher instance, the event listeners attached to - * it move along with it.

    - * - *

    If the event listener is being registered on a node while an event is also being processed - * on this node, the event listener is not triggered during the current phase but may be triggered - * during a later phase in the event flow, such as the bubbling phase.

    - * - *

    If an event listener is removed from a node while an event is being processed on the node, - * it is still triggered by the current actions. After it is removed, the event listener is never - * invoked again (unless it is registered again for future processing).

    - * - * @param event The type of event; {@link CollectionEvent.INSERT} or {@link CollectionEvent.ERASE}. - * @param listener The listener function that processes the event. - * This function must accept an Event object as its only parameter and must return - * nothing. - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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: "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; - /** - * 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. - * - * @param type The type of event; {@link CollectionEvent.INSERT} or {@link CollectionEvent.ERASE}. - * @param listener The listener object to remove. - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): 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. - * - * @param type The type of event; {@link CollectionEvent.INSERT} or {@link CollectionEvent.ERASE}. - * @param listener The listener object to remove. - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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 { /** * A {@link List} who can detect element I/O events. * + *
      + *
    • insert typed events:
        + *
      • {@link assign}
      • + *
      • {@link insert}
      • + *
      • {@link push}
      • + *
      • {@link push_front}
      • + *
      • {@link push_back}
      • + *
      • {@link merge}
      • + *
    • + *
    • erase typed events:
        + *
      • {@link assign}
      • + *
      • {@link clear}
      • + *
      • {@link erase}
      • + *
      • {@link pop_front}
      • + *
      • {@link pop_back}
      • + *
      • {@link unique}
      • + *
      • {@link remove}
      • + *
      • {@link remove_if}
      • + *
      • {@link splice}
      • + *
    • + *
    • erase typed events:
        + *
      • {@link sort}
      • + *
    • + *
    + * * @author Jeongho Nam */ class ListCollection extends std.List implements ICollection { @@ -772,47 +941,75 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.ListIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.ListIterator, last: std.ListIterator): void; /** * @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; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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: "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; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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 { /** * A {@link TreeMap} who can detect element I/O events. * + *
      + *
    • insert typed events:
        + *
      • {@link assign}
      • + *
      • {@link insert}
      • + *
      • {@link push}
      • + *
      • {@link set}
      • + *
      • {@link insert_or_assign}
      • + *
    • + *
    • erase typed events:
        + *
      • {@link assign}
      • + *
      • {@link clear}
      • + *
      • {@link erase}
      • + *
      • {@link extract}
      • + *
    • + *
    • refresh typed events:
        + *
      • {@link set}
      • + *
      • {@link insert_or_assign}
      • + *
    • + *
    + * * @author Jeongho Nam */ - class TreeMapCollection extends std.HashMap implements ICollection> { + class TreeMapCollection extends std.TreeMap implements ICollection> { /** * A chain object taking responsibility of dispatching events. */ @@ -833,45 +1030,68 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; /** * @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; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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: "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; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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 { /** * A {@link TreeMultiMap} who can detect element I/O events. * + *
      + *
    • insert typed events:
        + *
      • {@link assign}
      • + *
      • {@link insert}
      • + *
      • {@link push}
      • + *
    • + *
    • erase typed events:
        + *
      • {@link assign}
      • + *
      • {@link clear}
      • + *
      • {@link erase}
      • + *
    • + *
    + * * @author Jeongho Nam */ - class TreeMultiMapCollection extends std.HashMap implements ICollection> { + class TreeMultiMapCollection extends std.TreeMultiMap implements ICollection> { /** * A chain object taking responsibility of dispatching events. */ @@ -892,95 +1112,65 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; /** * @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; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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: "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; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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 { - /** - * A {@link TreeMap} who can detect element I/O events. - * - * @author Jeongho Nam - */ - class TreeSetCollection extends std.TreeSet implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: Event): boolean; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: EventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: EventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; - } /** * A {@link TreeMultiSet} who can detect element I/O events. * + *
      + *
    • insert typed events:
        + *
      • {@link assign}
      • + *
      • {@link insert}
      • + *
      • {@link push}
      • + *
    • + *
    • erase typed events:
        + *
      • {@link assign}
      • + *
      • {@link clear}
      • + *
      • {@link erase}
      • + *
    • + *
    + * * @author Jeongho Nam */ class TreeMultiSetCollection extends std.TreeMultiSet implements ICollection { @@ -1004,38 +1194,121 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; /** * @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; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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: "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: "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 { + /** + * A {@link TreeMap} who can detect element I/O events. + * + *
      + *
    • insert typed events:
        + *
      • {@link assign}
      • + *
      • {@link insert}
      • + *
      • {@link push}
      • + *
    • + *
    • erase typed events:
        + *
      • {@link assign}
      • + *
      • {@link clear}
      • + *
      • {@link erase}
      • + *
      • {@link extract}
      • + *
    • + *
    + * + * @author Jeongho Nam + */ + class TreeSetCollection extends std.TreeSet implements ICollection { + /** + * A chain object taking responsibility of dispatching events. + */ + private event_dispatcher_; /** * @inheritdoc */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + hasEventListener(type: string): boolean; /** * @inheritdoc */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @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; + /** + * @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; + /** + * @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; + /** + * @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; } } declare namespace samchon.library { @@ -1373,7 +1646,7 @@ declare namespace samchon.library { * * @author Jeongho Nam */ - class XMLList extends std.Vector { + class XMLList extends std.Deque { getTag(): string; /** *

    Convert XMLList to string.

    @@ -1390,6 +1663,30 @@ declare namespace samchon.library { } } declare namespace samchon.collection { + /** + * An {@link XMLList} who can detect element I/O events. + * + *

    Below are list of methods who are dispatching {@link CollectionEvent}:

    + * + *
      + *
    • insert typed events:
        + *
      • {@link assign}
      • + *
      • {@link insert}
      • + *
      • {@link push}
      • + *
      • {@link push_front}
      • + *
      • {@link push_back}
      • + *
    • + *
    • erase typed events:
        + *
      • {@link assign}
      • + *
      • {@link clear}
      • + *
      • {@link erase}
      • + *
      • {@link pop_front}
      • + *
      • {@link pop_back}
      • + *
    • + *
    + * + * @author Jeongho Nam + */ class XMLListCollection extends library.XMLList implements ICollection { /** * A chain object taking responsibility of dispatching events. @@ -1406,11 +1703,11 @@ declare namespace samchon.collection { /** * @hidden */ - protected insert_by_repeating_val(position: std.VectorIterator, n: number, val: library.XML): std.VectorIterator; + protected insert_by_repeating_val(position: std.DequeIterator, n: number, val: library.XML): std.DequeIterator; /** * @hidden */ - protected insert_by_range>(position: std.VectorIterator, begin: InputIterator, end: InputIterator): std.VectorIterator; + protected insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; /** * @inheritdoc */ @@ -1418,7 +1715,7 @@ declare namespace samchon.collection { /** * @hidden */ - protected erase_by_range(first: std.VectorIterator, last: std.VectorIterator): std.VectorIterator; + protected erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; /** * @hidden */ @@ -1435,71 +1732,57 @@ declare namespace samchon.collection { * @inheritdoc */ dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.DequeIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.DequeIterator, last: std.DequeIterator): void; /** * @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; /** * @inheritdoc */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: "insert" | "erase", listener: CollectionEventListener, 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: "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; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - unshift(...items: U[]): number; - /** - * @inheritdoc - */ - pop(): library.XML; - /** - * @inheritdoc - */ - splice(start: number): library.XML[]; - /** - * @inheritdoc - */ - splice(start: number, deleteCount: number, ...items: library.XML[]): library.XML[]; + 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.example { - function test_file_reference(): void; -} -declare namespace samchon.example { - function test_web_client(): void; -} declare namespace samchon.library { /** *

    Case generator.

    * - *

    CaseGenerator is an abstract case generator using like a matrix.

    + *

    {@link CaseGenerator} is an abstract case generator being used like a matrix.

    *
      - *
    • nTTr(n^r) -> CombinedPermutationGenerator
    • - *
    • nPr -> PermutationGenerator
    • - *
    • n! -> FactorialGenerator
    • + *
    • n��r(n^r) -> {@link CombinedPermutationGenerator}
    • + *
    • nPr -> {@link PermutationGenerator}
    • + *
    • n! -> {@link FactorialGenerator}
    • *
    * * @author Jeongho Nam @@ -1544,13 +1827,13 @@ declare namespace samchon.library { * @param index Index number * @return The row of the index'th in combined permuation case */ - abstract at(index: number): Array; + abstract at(index: number): number[]; } /** *

    A combined-permutation case generator.

    - *

    nTTr

    * - * @inheritdoc + *

    n��r

    + * * @author Jeongho Nam */ class CombinedPermutationGenerator extends CaseGenerator { @@ -1565,14 +1848,14 @@ declare namespace samchon.library { * @param r Size of elements of each case. */ constructor(n: number, r: number); - at(index: number): Array; + at(index: number): number[]; } /** *

    A permutation case generator.

    - *

    nPr

    + * + *

    nPr

    * * @author Jeongho Nam - * @inheritdoc */ class PermuationGenerator extends CaseGenerator { /** @@ -1585,8 +1868,15 @@ declare namespace samchon.library { /** * @inheritdoc */ - at(index: number): Array; + at(index: number): number[]; } + /** + *

    Factorial case generator.

    + * + *

    n! = nPn

    + * + * @author Jeongho Nam + */ class FactorialGenerator extends PermuationGenerator { /** * Construct from factorial size N. @@ -1602,8 +1892,8 @@ declare namespace samchon.library { * whether specific types of event listeners are registered, and dispatches events.

    * *

    Event targets are an important part of the Flash�� Player and Adobe AIR event model. The event - * target serves as the focal point for how events flow through the display list hierarchy. When an - * event such as a mouse click or a keypress occurs, an event object is dispatched into the event flow + * target serves as the local point for how events flow through the display list hierarchy. When an + * event such as a mouse click or a key press occurs, an event object is dispatched into the event flow * from the root of the display list. The event object makes a round-trip journey to the event target, * which is conceptually divided into three phases: the capture phase includes the journey from the * root to the last node before the event target's node; the target phase includes only the event @@ -1728,6 +2018,7 @@ declare namespace samchon.library { * @param listener The listener function that processes the event. * This function must accept an Event object as its only parameter and must return * nothing. + * @param thisArg The object to be used as the this object. */ addEventListener(type: string, listener: EventListener, thisArg: Object): void; /** @@ -1744,6 +2035,7 @@ declare namespace samchon.library { * * @param type The type of event. * @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; } @@ -1795,11 +2087,11 @@ declare namespace samchon.library { /** * The origin object who issuing events. */ - protected target: IEventDispatcher; + protected event_dispatcher_: IEventDispatcher; /** * Container of listeners. */ - protected listeners: std.HashMap>>; + protected event_listeners_: std.HashMap>>; /** * Default Constructor. */ @@ -1807,9 +2099,9 @@ declare namespace samchon.library { /** * Construct from the origin event dispatcher. * - * @param target The origin object who issuing events. + * @param dispatcher The origin object who issuing events. */ - constructor(target: IEventDispatcher); + constructor(dispatcher: IEventDispatcher); /** * @inheritdoc */ @@ -2011,6 +2303,31 @@ declare namespace samchon.library { * @param fileName File name to be saved. */ save(data: string, fileName: string): void; + /** + *

    Save a file to local filesystem.

    + * + *

    {@link FileReference.save} implemented the save function by downloading a file from a hidden anchor tag. + * However, the plan, future's {@link FileReference} will follow such rule:

    + * + *

    Opens a dialog box that lets the user save a file to the local filesystem.

    + * + *

    The {@link save save()} method first opens an browser-system dialog box that asks the user to enter a + * filename and select a location on the local computer to save the file. When the user selects a location and + * confirms the save operation (for example, by clicking Save), the save process begins. Listeners receive events + * to indicate the progress, success, or failure of the save operation. To ascertain the status of the dialog box + * and the save operation after calling {@link save save()}, your code must listen for events such as cancel, + * open, progress, and complete.

    + * + *

    When the file is saved successfully, the properties of the {@link FileReference} object are populated with + * the properties of the local file. The complete event is dispatched if the save is successful.

    + * + *

    Only one {@link browse browse()} or {@link save()} session can be performed at a time (because only one + * dialog box can be invoked at a time).

    + * + * @param data The data to be saved. The data can be in one of several formats, and will be treated appropriately. + * @param fileName File name to be saved. + */ + static save(data: string, fileName: string): void; } /** *

    The {@link FileReferenceList} class provides a means to let users select one or more files for @@ -2081,10 +2398,251 @@ declare namespace samchon.library { browse(...typeFilter: string[]): void; } } +declare namespace samchon.library { + /** + *

    A genetic algorithm class.

    + * + * @details + *

    In the field of artificial intelligence, a genetic algorithm (GA) is a search heuristic that mimics the + * process of natural selection. This heuristic (also sometimes called a metaheuristic) is routinely used to generate + * useful solutions to optimization and search problems.

    + * + *

    Genetic algorithms belong to the larger class of evolutionary algorithms (EA), which generate solutions to + * optimization problems using techniques inspired by natural evolution, such as inheritance, {@link mutate mutation}, + * {@link selection}, and {@link crossover}.

    + * + * @reference https://en.wikipedia.org/wiki/Genetic_algorithm + * @author Jeongho Nam + */ + class GeneticAlgorithm { + /** + * Whether each element (Gene) is unique in their GeneArray. + */ + private unique; + /** + * Rate of mutation. + * + * The {@link mutation_rate} determines the percentage of occurence of mutation in GeneArray. + * + *
      + *
    • When {@link mutation_rate} is too high, it is hard to ancitipate studying on genetic algorithm.
    • + *
    • + * When {@link mutation_rate} is too low and initial set of genes (GeneArray) is far away from optimal, the + * evolution tends to wandering outside of he optimal. + *
    • + *
    + */ + private mutation_rate; + /** + * Number of tournaments in selection. + */ + private tournament; + /** + * Initialization Constructor. + * + * @param unique Whether each Gene is unique in their GeneArray. + * @param mutation_rate Rate of mutation. + * @param tournament Number of tournaments in selection. + */ + constructor(unique?: boolean, mutation_rate?: number, tournament?: number); + /** + *

    Evolove GeneArray.

    + * + *

    Convenient method accessing to {@link evolvePopulation evolvePopulation()}.

    + * + * @param individual An initial set of genes; sequence listing. + * @param population Size of population in a generation. + * @param generation Size of generation in evolution. + * @param compare A comparison function returns whether left gene is more optimal. + * + * @return An evolved GeneArray, optimally. + * + * @see {@link GAPopulation.compare} + */ + evolveGeneArray>(individual: GeneArray, population: number, generation: number, compare?: (left: T, right: T) => boolean): GeneArray; + /** + * Evolve population, a mass of GeneArraies. + * + * @param population An initial population. + * @param compare A comparison function returns whether left gene is more optimal. + * + * @return An evolved population. + * + * @see {@link GAPopulation.compare} + */ + evolvePopulation>(population: GAPopulation, compare?: (left: T, right: T) => boolean): GAPopulation; + /** + *

    Select the best GeneArray in population from tournament.

    + * + *

    {@link selection Selection} is the stage of a genetic algorithm in which individual genomes are chosen + * from a population for later breeding (using {@linlk crossover} operator). A generic {@link selection} + * procedure may be implemented as follows:

    + * + *
      + *
    1. + * The fitness function is evaluated for each individual, providing fitness values, which are then + * normalized. ization means dividing the fitness value of each individual by the sum of all fitness + * values, so that the sum of all resulting fitness values equals 1. + *
    2. + *
    3. The population is sorted by descending fitness values.
    4. + *
    5. + * Accumulated normalized fitness values are computed (the accumulated fitness value of an individual is the + * sum of its own fitness value plus the fitness values of all the previous individuals). The accumulated + * fitness of the last individual should be 1 (otherwise something went wrong in the normalization step). + *
    6. + *
    7. A random number R between 0 and 1 is chosen.
    8. + *
    9. The selected individual is the first one whose accumulated normalized value is greater than R.
    10. + *
    + * + * @param population The target of tournament. + * @return The best genes derived by the tournament. + * + * @reference https://en.wikipedia.org/wiki/Selection_(genetic_algorithm) + */ + private selection(population); + /** + *

    Create a new GeneArray by crossing over two GeneArray(s).

    + * + *

    {@link crossover} is a genetic operator used to vary the programming of a chromosome or chromosomes from + * one generation to the next. It is analogous to reproduction and biological crossover, upon which genetic + * algorithms are based.

    + * + *

    {@link crossover Cross over} is a process of taking more than one parent solutions and producing a child + * solution from them. There are methods for selection of the chromosomes.

    + * + * @param parent1 A parent sequence listing + * @param parent2 A parent sequence listing + * + * @reference https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm) + */ + private crossover(parent1, parent2); + /** + *

    Cause a mutation on the GeneArray.

    + * + *

    {@link mutate Mutation} is a genetic operator used to maintain genetic diversity from one generation of a + * population of genetic algorithm chromosomes to the next. It is analogous to biological mutation.

    + * + *

    {@link mutate Mutation} alters one or more gene values in a chromosome from its initial state. In + * {@link mutate mutation}, the solution may change entirely from the previous solution. Hence GA can come to + * better solution by using {@link mutate mutation}.

    + * + *

    {@link mutate Mutation} occurs during evolution according to a user-definable mutation probability. This + * probability should be set low. If it is set too high, the search will turn into a primitive random search.

    + * + *

    Note

    + *

    Muttion is pursuing diversity. Mutation is useful for avoiding the following problem.

    + * + *

    When initial set of genes(GeneArray) is far away from optimail, without mutation (only with selection and + * crossover), the genetic algorithm has a tend to wandering outside of the optimal.

    + * + *

    Genes in the GeneArray will be swapped following percentage of the {@link mutation_rate}.

    + * + * @param individual A container of genes to mutate + * + * @reference https://en.wikipedia.org/wiki/Mutation_(genetic_algorithm) + * @see {@link mutation_rate} + */ + private mutate(individual); + } + /** + *

    A population in a generation.

    + * + *

    {@link GAPopulation} is a class representing population of candidate genes (sequence listing) having an array + * of GeneArray as a member. {@link GAPopulation} also manages initial set of genes and handles fitting test direclty + * by the method {@link fitTest fitTest()}.

    + * + *

    The success of evolution of genetic algorithm is depend on the {@link GAPopulation}'s initial set and fitting + * test. (GeneArray and {@link compare}.)

    + * + *

    Warning

    + *

    Be careful for the mistakes of direction or position of the {@link compare}.

    + *

    Most of logical errors failed to access optimal solution are occured from those mistakes.

    + * + * @param Type of gene elements. + * @param An array containing genes as elments; sequnce listing. + * + * @author Jeongho Nam + */ + class GAPopulation> { + /** + * Genes representing the population. + */ + private children; + /** + *

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

    + * + *

    Default value of this {@link compare} is {@link std.greater}. It means to compare two array + * (GeneArray must be a type of {@link std.base.IArrayContainer}). Thus, you've to keep follwing rule.

    + * + *
      + *
    • GeneArray is implemented from {@link std.base.IArrayContainer}.
    • + *
        + *
      • {@link std.Vector}
      • + *
      • {@link std.Deque}
      • + *
      + *
    • GeneArray has custom public less(obj: T): boolean; function.
    • + *
    + * + *

    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 constructor with population.

    + * + *

    Private constructor of GAPopulation does not create {@link children}. (candidate genes) but only assigns + * null repeatedly following the population size.

    + * + *

    This private constructor is designed only for {@link GeneticAlgorithm}. Don't create {@link GAPopulation} + * with this constructor, by yourself.

    + * + * @param size Size of the population. + */ + constructor(size: number); + /** + *

    Construct from a {@link GeneArray} and size of the population.

    + * + *

    This public constructor creates GeneArray(s) as population (size) having shuffled genes which are + * came from the initial set of genes (geneArray). It uses {@link std.greater} as default comparison function. + *

    + * + * @param geneArray An initial sequence listing. + * @param size The size of population to have as children. + */ + constructor(geneArray: GeneArray, size: number); + /** + *

    Constructor from a GeneArray, size of the poluation and custom comparison function.

    + * + *

    This public constructor creates GeneArray(s) as population (size) having shuffled genes which are + * came from the initial set of genes (geneArray). The compare is used for comparison function. + *

    + * + * @param geneArray An initial sequence listing. + * @param size The size of population to have as children. + * @param compare A comparison function returns whether left gene is more optimal. + */ + constructor(geneArray: GeneArray, size: number, compare: (left: GeneArray, right: GeneArray) => boolean); + /** + * Test fitness of each GeneArray in the {@link population}. + * + * @return The best GeneArray in the {@link population}. + */ + fitTest(): GeneArray; + /** + * @hidden + */ + private clone(obj); + } +} declare namespace samchon.library { /** *

    A utility class supporting static methods of string.

    * + *

    The {@link StringUtil} utility class is an all-static class with methods for working with string objects within + * Samchon Framework. You do not create instances of {@link StringUtil}; instead you call methods such as the + * StringUtil.substitute() method.

    + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/utils/StringUtil.html * @author Jeongho Nam */ class StringUtil { @@ -2105,11 +2663,11 @@ declare namespace samchon.library { *
  • If start and end are all omitted, returns str, itself.
  • *
* - * @param str Target string to be applied between - * @param start A string for separating substring at the front - * @param end A string for separating substring at the end + * @param str Target string to be applied between. + * @param start A string for separating substring at the front. + * @param end A string for separating substring at the end. * - * @return substring by specified terms + * @return substring by specified terms. */ static between(str: string, start?: string, end?: string): string; /** @@ -2124,12 +2682,12 @@ declare namespace samchon.library { *
  • If startStr and endStar are all omitted, returns str.
  • * * - * @param str Target string to split by between + * @param str Target string to split by between. * @param start A string for separating substring at the front. - * If omitted, it's same with split(end) not having last item + * If omitted, it's same with split(end) not having last item. * @param end A string for separating substring at the end. - * If omitted, it's same with split(start) not having first item - * @return An array of substrings + * If omitted, it's same with split(start) not having first item. + * @return An array of substrings. */ static betweens(str: string, start?: string, end?: string): Array; /** @@ -2195,20 +2753,74 @@ declare namespace samchon.library { * @return A string specified words are replaced */ static replaceAll(str: string, ...pairs: std.Pair[]): string; - /** - *

    Get a tabbed string by specified size.

    - */ - static tab(size: number): string; - /** - *

    Get a tabbed HTLM string by specified size.

    - */ - static htmlTab(size: number): string; /** * Replace all HTML spaces to a literal space. * * @param str Target string to replace. */ static removeHTMLSpaces(str: string): string; + /** + *

    Repeat a string.

    + * + *

    Returns a string consisting of a specified string concatenated with itself a specified number of times.

    + * + * @param str The string to be repeated. + * @param n The repeat count. + * + * @return The repeated string. + */ + static repeat(str: string, n: number): string; + /** + *

    Number to formatted string with "," sign.

    + * + *

    Returns a string converted from the number rounded off from specified precision with "," symbols.

    + * + * @param val A number wants to convert to string. + * @param precision Target precision of round off. + * + * @return A string who represents the number with roundoff and "," symbols. + */ + static numberFormat(val: number, precision?: number): string; + static percentFormat(val: number, precision?: number): string; + } +} +declare namespace samchon.library { + /** + *

    URLVariables class is for representing variables of HTTP.

    + * + *

    URLVariables class allows you to transfer variables between an application and server. + * When transfering, URLVariables will be converted to a URI string.

    + * + *
      + *
    • URI: Uniform Resource Identifier
    • + *
    + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLVariables.html + * @author Migrated by Jeongho Nam + */ + class URLVariables extends std.HashMap { + /** + * Default Constructor. + */ + constructor(); + /** + *

    Construct from a URL-encoded string.

    + * + *

    The {@link decode decode()} method is automatically called to convert the string to properties of the {@link URLVariables} object.

    + * + * @param str A URL-encoded string containing name/value pairs. + */ + constructor(str: string); + /** + * Converts the variable string to properties of the specified URLVariables object. + * + * @param str A URL-encoded query string containing name/value pairs. + */ + decode(str: string): void; + /** + * Returns a string containing all enumerable variables, in the MIME content encoding application/x-www-form-urlencoded. + */ + toString(): string; } } declare namespace samchon.protocol { @@ -2247,20 +2859,31 @@ declare namespace samchon.protocol { * * @param xml An xml used to contruct data of entity. */ - construct(xml: library.XML): any; + construct(xml: library.XML): void; /** *

    Get a key that can identify the Entity uniquely.

    * - *

    If identifier of the Entity is not atomic value, returns a string or paired object + *

    If identifier of the Entity is not atomic value, returns a paired or tuple object * that can represents the composite identifier.

    + * + * + * class Point extends Entity + * { + * private x: number; + * private y: number; + * + * public key(): std.Pair + * { + * return std.make_pair(this.x, this.y); + * } + * } + * */ key(): any; /** *

    A tag name when represented by XML.

    * - *
      - *
    • - *
    + * */ TAG(): string; /** @@ -2345,6 +2968,593 @@ declare namespace samchon.protocol { toXML(): library.XML; } } +declare namespace samchon.protocol { + /** + *

    An interface taking full charge of network communication.

    + * + *

    {@link ICommunicator} is an interface for communicator classes who take full charge of network communication + * with external system, without reference to whether the external system is a server or a client.

    + * + *

    Whenever a replied message comes from the external system, the message will be converted to an + * {@link Invoke} class and will be shifted to the {@link WebCommunicator.listener listener}'s + * {@link IProtocol.replyData replyData()} method.

    + * + * + interface ICommmunicator + { + private socket: SomeSocketClass; + + // LISTENER LISTENS INVOKE MESSAGE BY IT'S IProtocol.replyData() METHOD + protected listener: IProtocol; + + // YOU CAN DETECT DISCONNECTION BY ENROLLING FUNCTION POINTER TO HERE. + public onClose: Function; + + public sendData(invoke: Invoke): void + { + this.socket.write(invoke); + } + public replyData(invoke: Invoke): void + { + // WHENEVER COMMUNICATOR GETS MESSAGE, THEN SHIFT IT TO LISTENER'S replyData() METHOD. + this.listener.replyData(invoke); + } + } + * + * + *

    + * + *

    + * + * + *

    Basic Components

    + *

    What Basic Components are

    + *

    Basic Components are the smallest unit of network communication in this Samchon Framework. With + * Basic Components, you can construct any type of network system, even how the network system is enormously + * scaled and complicated, by just combinating the Basic Components.

    + * + *

    All the system templates in this framework are also being implemented by utilization of the + * Basic Compoonents.

    + * + *
      + *
    • {@link service Service} + *
    • {@link external External System} + *
    • {@link parallel Parallel System} + *
    • {@link distributed Distributed System} + *
    + * + *

    Note that, whatever the network system what you've to construct is, just concentrate on role of each system + * and attach matched Basic Components to the role, within framework of the Object-Oriented Design. + * Then construction of the network system will be much easier.

    + * + *
      + *
    • A system is a server, then use {@link IServer} or {@link IServerBase}.
    • + *
    • A server wants to handle a client has connected, then use {@link IClientDriver}.
    • + *
    • A system is a client connecting to an external server, then use {@link IServerConnector}.
    • + *
    • + *
    + * + *

    Example - System Templates

    + *

    Learning and understanding Basic Components of Samchon Framework, reading source codes and design of + * System Templates' modules will be very helpful.

    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Name Source API Documents
    Cloud Service protocol/service {@link protocol.service}
    External System protocol/external {@link protocol.external}
    Parallel System protocol/parallel {@link protocol.parallel}
    Distributed System protocol/distributed {@link protocol.distributed}
    Slave System protocol/slave {@link protocol.slave}
    + * + *

    Example - Projects

    + * + * + * @see {@link IClientDriver}, {@link IServerConnector} + * @handbook Basic Components - ICommunicator + * @author Jeongho Nam + */ + interface ICommunicator extends IProtocol { + /** + * Callback function for connection closed. + */ + onClose: Function; + /** + * Close connection. + */ + close(): any; + sendData(invoke: protocol.Invoke): void; + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.protocol { + abstract class CommunicatorBase implements ICommunicator { + /** + * @hidden + */ + protected listener: IProtocol; + /** + * @inheritdoc + */ + onClose: Function; + /** + * @hidden + */ + private binary_invoke; + /** + * @hidden + */ + private binary_parameters; + /** + * @hidden + */ + private unhandled_invokes; + /** + * Default Constructor. + */ + constructor(); + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + abstract close(): void; + protected is_binary_invoke(): boolean; + abstract sendData(invoke: Invoke): void; + replyData(invoke: Invoke): void; + protected handle_string(str: string): void; + protected handle_binary(binary: Uint8Array): void; + } +} +declare namespace samchon.protocol { + class Communicator extends CommunicatorBase { + /** + * @hidden + */ + protected socket: socket.socket; + /** + * @hidden + */ + private header_bytes; + /** + * @hidden + */ + private data; + /** + * @hidden + */ + private data_index; + /** + * @hidden + */ + private listening; + /** + * @inheritdoc + */ + close(): void; + /** + * @hidden + */ + protected start_listen(): void; + /** + * @hidden + */ + private handle_error(); + /** + * @hidden + */ + private handle_close(); + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + * @hidden + */ + private listen_piece(piece); + /** + * @hidden + */ + private listen_header(piece, piece_index); + /** + * @hidden + */ + private listen_data(piece, piece_index); + } +} +declare namespace samchon.protocol { + /** + *

    Base class for web-communicator, {@link WebClientDriver} and {@link WebServerConnector}.

    + * + *

    This class {@link WebCommunicatorBase} subrogates network communication for web-communicator classes, + * {@link WebClinetDriver} and {@link WebServerConnector}. The web-communicator and this class + * {@link WebCommunicatorBase} share same interface {@link IProtocol} and have a chain of responsibily + * relationship.

    + * + *

    When an {@link Invoke} message was delivered from the connected remote system, then this class calls + * web-communicator's {@link WebServerConnector.replyData replyData()} method. Also, when called web-communicator's + * {@link WebClientDriver.sendData sendData()}, then {@link sendData sendData()} of this class will be caleed.

    + * + *
      + *
    • this.replyData() -> communicator.replyData()
    • + *
    • communicator.sendData() -> this.sendData()
    • + *
    + * + * @author Jeongho Nam + */ + class WebCommunicator extends CommunicatorBase { + /** + * Connection driver, a socket for web-socket. + */ + protected connection: websocket.connection; + /** + * Close the connection. + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + *

    Handle raw-data received from the remote system.

    + * + *

    Queries raw-data received from the remote system. When the raw-data represents an formal {@link Invoke} + * message, then it will be sent to the {@link replyData}.

    + * + * @param message A raw-data received from the remote system. + */ + protected handle_message(message: websocket.IMessage): void; + protected handle_close(): void; + } +} +declare namespace samchon.protocol { + class SharedWorkerCommunicator extends CommunicatorBase { + protected port: MessagePort; + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + protected handle_message(event: MessageEvent): void; + } +} +declare namespace samchon.protocol { + /** + *

    An interface for communicator with connected client.

    + * + *

    {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with connected client + * in a server. It takes full charge of network communication with the connected client.

    + * + *

    {@link IClientDriver} is created in {@link IServer} and delivered via + * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being + * created by matched {@link IServer} object.

    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Derived Type Created By
    {@link ClientDrvier} {@link Server}
    {@link WebClientDrvier} {@link WebServer}
    {@link SharedWorkerClientDrvier} {@link SharedWorkerServer}
    + * + *

    + * + *

    + * + *

    When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then + * specify {@link CommunicatorBase.listener listener} with {@link IClient.listen IClient.listen()}. Below codes are + * an example specifying and managing the {@link CommunicatorBase.listener listener} objects.

    + * + * + /// + /// + + // IMPORTS + import std = require("typescript-stl"); + import samchon = require("samchon-framework"); + + // SHORTCUTS + import library = samchon.library; + import protocol = samchon.protocol; + + class CalculatorServer extends protocol.Server + { + private clients: std.HashSet; + + // WHEN A CLIENT HAS CONNECTED + public addClient(driver: IClientDriver): void + { + let client: CalculatorClient = new CalculatorClient(this, driver); + this.clients.insert(client); + } + } + + class CalculatorClient extends protocol.IProtocol + { + // PARENT SERVER INSTANCE + private server: CalculatorServer; + + // COMMUNICATOR, SENDS AND RECEIVES NETWORK MESSAGE WITH CONNECTED CLIENT + private driver: protocol.IClientDriver; + + ///// + // CONSTRUCTORS + ///// + public constructor(server: CalculatorServer, driver: protocol.IClientDriver) + { + this.server = server; + this.driver = driver; + + // START LISTENING AND RESPOND CLOSING EVENT + this.driver.listen(this); // INVOKE MESSAGE WILL COME TO HERE + this.driver.onClose = this.destructor.bind(this); // DISCONNECTED HANDLER + } + public destructor(): void + { + // WHEN DISCONNECTED, THEN ERASE THIS OBJECT FROM CalculatorServer.clients. + this.server["clients"].erase(this); + } + + ///// + // INVOKE MESSAGE CHAIN + ///// + public sendData(invoke: protocol.Invoke): void + { + // CALL ICommunicator.sendData(), WHO PHYSICALLY SEND NETWORK MESSAGE + this.driver.sendData(invoke); + } + public replyData(invoke: protocol.Invoke): void + { + // FIND MATCHED MEMBER FUNCTION NAMED EQUAL TO THE invoke.getListener() + invoke.apply(this); + } + } + * + * + * + *

    Basic Components

    + *

    What Basic Components are

    + *

    Basic Components are the smallest unit of network communication in this Samchon Framework. With + * Basic Components, you can construct any type of network system, even how the network system is enormously + * scaled and complicated, by just combinating the Basic Components.

    + * + *

    All the system templates in this framework are also being implemented by utilization of the + * Basic Compoonents.

    + * + *
      + *
    • {@link service Service} + *
    • {@link external External System} + *
    • {@link parallel Parallel System} + *
    • {@link distributed Distributed System} + *
    + * + *

    Note that, whatever the network system what you've to construct is, just concentrate on role of each system + * and attach matched Basic Components to the role, within framework of the Object-Oriented Design. + * Then construction of the network system will be much easier.

    + * + *
      + *
    • A system is a server, then use {@link IServer} or {@link IServerBase}.
    • + *
    • A server wants to handle a client has connected, then use {@link IClientDriver}.
    • + *
    • A system is a client connecting to an external server, then use {@link IServerConnector}.
    • + *
    • + *
    + * + *

    Example - System Templates

    + *

    Learning and understanding Basic Components of Samchon Framework, reading source codes and design of + * System Templates' modules will be very helpful.

    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Name Source API Documents
    Cloud Service protocol/service {@link protocol.service}
    External System protocol/external {@link protocol.external}
    Parallel System protocol/parallel {@link protocol.parallel}
    Distributed System protocol/distributed {@link protocol.distributed}
    Slave System protocol/slave {@link protocol.slave}
    + * + *

    Example - Projects

    + * + * + * @see {@link IServer} + * @handbook Basic Components - IClientDriver + * @author Jeongho Nam + */ + interface IClientDriver extends ICommunicator { + /** + *

    Listen message from the newly connected client.

    + * + *

    Starts listening message from the newly connected client. Replied message from the connected client will + * be converted to {@link Invoke} classes and shifted to the listener's + * {@link IProtocol.replyData replyData()} method.

    + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} message. + */ + listen(listener: IProtocol): void; + } +} +declare namespace samchon.protocol { + class ClientDriver extends Communicator implements IClientDriver { + constructor(socket: socket.socket); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + } +} +declare namespace samchon.protocol { + class WebClientDriver extends WebCommunicator implements IClientDriver { + /** + * Requested path. + */ + private path; + /** + * Session ID, an identifier of the remote client. + */ + private session_id; + private listening; + /** + * Initialization Constructor. + * + * @param connection Connection driver, a socket for web-socket. + * @param path Requested path. + * @param session_id Session ID, an identifier of the remote client. + */ + constructor(connection: websocket.connection, path: string, session_id: string); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + /** + * Get requested path. + */ + getPath(): string; + /** + * Get session ID, an identifier of the remote client. + */ + getSessionID(): string; + } +} +declare namespace samchon.protocol { + class SharedWorkerClientDriver extends SharedWorkerCommunicator implements IClientDriver { + private listening; + constructor(port: MessagePort); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + } +} +declare namespace samchon.protocol { + abstract class DedicatedWorker implements IProtocol { + private communicator_; + /** + * Default Constructor. + */ + constructor(); + abstract replyData(invoke: protocol.Invoke): void; + sendData(invoke: Invoke): void; + } +} +declare namespace samchon.protocol { + class DedicatedWorkerConnector extends CommunicatorBase implements IServerConnector { + private worker; + /** + * @inheritdoc + */ + onConnect: Function; + /** + * @inheritdoc + */ + onClose: Function; + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + connect(jsFile: string): void; + /** + * @inheritdoc + */ + close(): void; + sendData(invoke: Invoke): void; + replyData(invoke: Invoke): void; + private handle_message(event); + } +} declare namespace samchon.protocol { interface IEntityGroup extends IEntity, std.base.IContainer { /** @@ -2368,7 +3578,6 @@ declare namespace samchon.protocol { * * @return A new child Entity belongs to EntityArray. */ - createChild(xml: library.XML): T; /** *

    Get iterator to element.

    * @@ -2444,9 +3653,15 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - * @inheritdoc + *

    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. */ - abstract createChild(xml: library.XML): T; + protected abstract createChild(xml: library.XML): T; /** * @inheritdoc */ @@ -2488,9 +3703,15 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - * @inheritdoc + *

    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. */ - abstract createChild(xml: library.XML): T; + protected abstract createChild(xml: library.XML): T; /** * @inheritdoc */ @@ -2532,9 +3753,15 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - * @inheritdoc + *

    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. */ - abstract createChild(xml: library.XML): T; + protected abstract createChild(xml: library.XML): T; /** * @inheritdoc */ @@ -2583,9 +3810,15 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - * @inheritdoc + *

    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. */ - abstract createChild(xml: library.XML): T; + protected abstract createChild(xml: library.XML): T; /** * @inheritdoc */ @@ -2627,9 +3860,15 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - * @inheritdoc + *

    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. */ - abstract createChild(xml: library.XML): T; + protected abstract createChild(xml: library.XML): T; /** * @inheritdoc */ @@ -2671,9 +3910,15 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - * @inheritdoc + *

    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. */ - abstract createChild(xml: library.XML): T; + protected abstract createChild(xml: library.XML): T; /** * @inheritdoc */ @@ -2709,203 +3954,238 @@ declare namespace samchon.protocol { } declare namespace samchon.protocol { /** - *

    A network driver for an external system.

    + *

    An interface for {@link Invoke} message chain.

    * - *

    ExternalSystem is a boundary class interacting with an external system by network communication. - * Also, ExternalSystem is an abstract class that a network role, which one is server and which one is - * client, is not determined yet.

    + *

    {@link IProtocol} is an interface for {@link Invoke} message, which is standard message of network I/O in + * Samchon Framework, chain. The {@link IProtocol} interface is used to network drivers and some classes + * which are in a relationship of Chain of Responsibility Pattern with those network drivers.

    * - *

    The ExternalSystem has ExternalSystemRole(s) groupped methods, handling Invoke message - * interacting with the external system, by subject or unit of a moudle. The ExternalSystemRole is - * categorized in a 'control'.

    + *

    Implements {@link IProtocol} if the class sends and handles {@link Invoke} message. Looking around source + * codes of Samchon Framework, especially System Templates, you can find out that all the classes and + * modules handling {@link Invoke} messages are always implementing this {@link IProtocol} . Yes, {@link IProtocol}, + * this is the main role you've to follow in this Samchon Framework.

    * - *

    Note

    - *

    The ExternalSystem class takes a role of interaction with external system in network level. - * However, within a framework of Samchon Framework, a boundary class like the ExternalSystem is - * not such important. You can find some evidence in a relationship between ExternalSystemArray, - * ExternalSystem and ExternalSystemRole.

    + *

    + * + *

    * - *

    Of course, the ExternalSystemRole is belonged to an ExternalSystem. However, if you - * access an ExternalSystemRole from an ExternalSystemArray directly, not passing by a belonged - * ExternalSystem, and send an Invoke message even you're not knowing which ExternalSystem is - * related in, it's called "Proxy pattern". * - *

    Like the explanation of "Proxy pattern", you can utilize an ExternalSystemRole as a proxy - * of an ExternalSystem. With the pattern, you can only concentrate on ExternalSystemRole itself, - * what to do with Invoke message, irrespective of the ExternalSystemRole is belonged to which - * ExternalSystem.

    - * - * @author Jeongho Nam - */ - abstract class ExternalSystem extends EntityArray implements IProtocol { - /** - *

    A driver for interacting with (real, physical) external system.

    - */ - protected driver: ServerConnector; - /** - *

    A name can identify an external system.

    - * - *

    The name must be unique in ExternalSystemArray.

    - */ - protected name: string; - /** - *

    An ip address of an external system.

    - */ - protected ip: string; - /** - *

    A port number of an external system.

    - */ - protected port: number; - /** - *

    Default Constructor.

    - */ - constructor(); - /** - *

    Start interaction.

    - *

    An abstract method starting interaction with an external system.

    - * - *

    If an external systems are a server, starts connection and listening Inovoke message, - * else clients, just starts listening only. You also can addict your own procudures of starting - * the driver, but if you directly override method of abstract ExternalSystem, be careful about - * virtual inheritance.

    - */ - start(): void; - key(): any; - /** - *

    Get name.

    - */ - getName(): string; - /** - *

    Get ip address of the external system.

    - */ - getIP(): string; - /** - *

    Get port number of the external system.

    - */ - getPort(): number; - sendData(invoke: Invoke): void; - replyData(invoke: Invoke): void; - TAG(): string; - CHILD_TAG(): string; - } -} -declare namespace samchon.protocol { - /** - *

    An array of ExternalSystem(s).

    - * - *

    ExternalSystemArray is an abstract class containing and managing external system drivers.

    - * - *

    Also, ExternalSystemArray can access to ExternalSystemRole(s) directly. With the method, you - * can use an ExternalSystemRole as "logical proxy" of an ExternalSystem. Of course, the - * ExternalSystemRole is belonged to an ExternalSystem. However, if you access an ExternalSystemRole - * from an ExternalSystemArray directly, not passing by a belonged ExternalSystem, and send an Invoke - * message even you're not knowing which ExternalSystem is related in, the ExternalSystemRole acted - * a role of proxy.

    - * - *

    It's called as "Proxy pattern". With the pattern, you can only concentrate on - * ExternalSystemRole itself, what to do with Invoke message, irrespective of the ExternalSystemRole - * is belonged to which ExternalSystem.

    + *

    Utilization Case

    + *

    Below pseudo code and class diagram represents {@link service Service Module}, who can build a cloud server. + * All the classes in the pseudo code are implementing the {@link IProtocol} because all of them are handling + * {@link Invoke} message.

    * *
      - *
    • ExternalSystemArray::getRole("something")->sendData(invoke);
    • + *
    • Server: Represents a server literally
    • + *
    • User: Represents an user being identified by its session id. User contains multiple Client objects.
    • + *
        + *
      • In browser, an user can open multiple windows. + *
          + *
        • User: A browser (like IE, Chrome and Safari). + *
        • Client: An internet browser window + *
        + *
      • + *
      + *
    • Client: Represents a browser window and it takes role of network communication with it.
    • + *
    • Service: Represents a service, domain logic.
    • *
    * - * @author Jeongho Nam - */ - abstract class ExternalSystemArray extends EntityArray implements IProtocol { - /** - * Default Constructor. - */ - constructor(); - /** - *

    Start interaction.

    - *

    An abstract method starting interaction with external systems.

    - * - *

    If external systems are servers, starts connection to them, else clients, opens a server - * and accepts the external systems. You can addict your own procudures of starting drivers, but - * if you directly override method of abstract ExternalSystemArray, be careful about virtual - * inheritance.

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

    Test whether has a role.

    - * - * @param name Name of an ExternalSystemRole. - * @return Whether has or not. - */ - hasRole(key: string): boolean; - /** - *

    Get a role.

    - * - * @param name Name of an ExternalSystemRole - * @return A shared pointer of specialized role - */ - getRole(key: string): ExternalSystemRole; - sendData(invoke: Invoke): void; - replyData(invoke: Invoke): void; - TAG(): string; - CHILD_TAG(): string; + *

    + * + *

    + * + * + /// + /// + + // IMPORTS + import std = require("typescript-stl"); + import samchon = require("samchon-framework"); + + // SHORTCUTS + import library = samchon.library; + import collection = samchon.collection; + import protocol = samchon.protocol; + + namespace service + { + export class Server extends protocol.WebServer implements IProtocol + { + // SERVER HAS MULTIPLE USER OBJECTS + private session_map: std.HashMap; + + //------------------------ + // MESSAGE CHAIN + //------------------------ + public sendData(invoke: protocol.Invoke): void + { + // SEND INVOKE MESSAGE TO ALL USER OBJECTS + for (let it = this.session_map.begin(); !it.equal_to(this.session_map.end()); it = it.next()) + it.second.sendData(invoke); + } + public replyData(invoke: protocol.Invoke): void + { + invoke.apply(this); // HANDLE INVOKE MESSAGE BY ITSELF + } + } + + export class User extends + collection.HashMapCollection // USER HAS MULTIPLE CLIENT OBJECTS + implements IProtocol + { + private server: Server; // USER REFRES SERVER + + //------------------------ + // MESSAGE CHAIN + //------------------------ + public sendData(invoke: protocol.Invoke): void + { + // SEND INVOKE MESSAGE TO ALL CLIENT OBJECTS + for (let it = this.begin(); !it.equal_to(this.end()); it = it.next()) + it.second.sendData(invoke); + } + public replyData(invoke: protocol.Invoke): void + { + invoke.apply(this); // HANDLE INOVKE MESSAGE BY ITSELF + this.server.replyData(invoke); // OR VIA SERVER + } + } + + export class Client implements IProtocol + { + private user: User; // CLIENT REFERS USER + private service: Service; // CLIENT HAS A SERVICE OBJECT + + private driver: WebClientDriver; + + //------------------------ + // MESSAGE CHAIN + //------------------------ + public sendData(invoke: protocol.Invoke): void + { + // SEND INVOKE MESSAGE VIA driver: WebClientDriver + this.driver.sendData(invoke); + } + public replyData(invoke: protocol.Invoke): void + { + invoke.apply(this); // HANDLE INOVKE MEESAGE BY ITSELF + this.user.replyData(invoke); // OR VIA USER + + if (this.service != null) // OR VIA SERVICE + this.service.replyData(invoke); + } + } + + export class Service implements IProtocol + { + private client: Client; // SERVICE REFRES CLIENT + + //------------------------ + // MESSAGE CHAIN + //------------------------ + public sendData(invoke: protocol.Invoke): void + { + // SEND INVOKE MESSAGE VIA CLIENT + return this.client.sendData(invoke); + } + public replyData(invoke: protocol.Invoke): void + { + invoke.apply(this); // HANDLE INVOKE MESSAGE BY ITSELF + } + } } -} -declare namespace samchon.protocol { - /** - *

    A role belongs to an external system.

    + *
    * - *

    ExternalSystemRole is a 'control' class groupping methods, handling Invoke messages - * interacting with an external system that the ExternalSystemRole is belonged to, by a subject or - * unit of a module.

    * - *

    ExternalSystemRole can be a "logical proxy" for an ExternalSystem which is containing the - * ExternalSystemRole. Of course, the ExternalSystemRole is belonged to an ExternalSystem. However, - * if you access an ExternalSystemRole from an ExternalSystemArray directly, not passing by a - * belonged ExternalSystem, and send an Invoke message even you're not knowing which ExternalSystem - * is related in, the ExternalSystemRole acted a role of proxy.

    + *

    Basic Components

    + *

    What Basic Components are

    + *

    Basic Components are the smallest unit of network communication in this Samchon Framework. With + * Basic Components, you can construct any type of network system, even how the network system is enormously + * scaled and complicated, by just combinating the Basic Components.

    * - *

    It's called as "Proxy pattern". With the pattern, you can only concentrate on - * ExternalSystemRole itself, what to do with Invoke message, irrespective of the ExternalSystemRole - * is belonged to which ExternalSystem.

    + *

    All the system templates in this framework are also being implemented by utilization of the + * Basic Compoonents.

    * - * @author Jeongho Nam - */ - class ExternalSystemRole extends Entity implements IProtocol { - /** - *

    A driver of external system containing the ExternalSystemRole.

    - */ - protected system: ExternalSystem; - /** - *

    A name representing the role.

    - */ - protected name: string; - protected sendListeners: std.HashSet; - /** - *

    Construct from external system driver.

    - * - * @param system A driver of external system the ExternalSystemRole is belonged to. - */ - constructor(system: ExternalSystem); - construct(xml: library.XML): void; - getName(): string; - hasSendListener(key: string): boolean; - sendData(invoke: Invoke): void; - replyData(invoke: Invoke): void; - TAG(): string; - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - *

    An interface for Invoke message chain.

    + *
      + *
    • {@link service Service} + *
    • {@link external External System} + *
    • {@link parallel Parallel System} + *
    • {@link distributed Distributed System} + *
    * - *

    IProtocol is an interface for Invoke message, which is standard message of network I/O - * in Samchon Framework, chain. The IProtocol interface is used to network drivers and some - * classes which are in a relationship of chain of responsibility with those network drivers.

    + *

    Note that, whatever the network system what you've to construct is, just concentrate on role of each system + * and attach matched Basic Components to the role, within framework of the Object-Oriented Design. + * Then construction of the network system will be much easier.

    * - *

    In Samchon Framework, server side, IProtocol is one of the basic 3 + 1 components that - * can make any type of network system in Samchon Framework with IServer and IClient. Following - * the "chain of responsibility" pa1ttern, looking around classes in Samchon Framework, you - * can see all related classes with network I/O are implemented from the IProtocol.

    + *
      + *
    • A system is a server, then use {@link IServer} or {@link IServerBase}.
    • + *
    • A server wants to handle a client has connected, then use {@link IClientDriver}.
    • + *
    • A system is a client connecting to an external server, then use {@link IServerConnector}.
    • + *
    • + *
    * - * @see Invoke + *

    Example - System Templates

    + *

    Learning and understanding Basic Components of Samchon Framework, reading source codes and design of + * System Templates' modules will be very helpful.

    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Name Source API Documents
    Cloud Service protocol/service {@link protocol.service}
    External System protocol/external {@link protocol.external}
    Parallel System protocol/parallel {@link protocol.parallel}
    Distributed System protocol/distributed {@link protocol.distributed}
    Slave System protocol/slave {@link protocol.slave}
    + * + *

    Example - Projects

    + * + * + * @see {@link Invoke} + * @handbook Basic Components - IProtocol * @author Jeongho Nam */ interface IProtocol { @@ -2920,7 +4200,7 @@ declare namespace samchon.protocol { *

    Handling replied message.

    *

    Handles replied message or shifts the responsibility to chain.

    * - * @param invoke Replied invoke message + * @param invoke An {@link Invoke} message has received. */ sendData(invoke: Invoke): void; } @@ -2928,7 +4208,8 @@ declare namespace samchon.protocol { declare namespace samchon.protocol { /** *

    Standard message of network I/O.

    - *

    Invoke is a class used in network I/O in protocol package of Samchon Framework.

    + * + *

    {@link Invoke} is a class used in network I/O in protocol package of Samchon Framework.

    * *

    The Invoke message has an XML structure like the result screen of provided example in below. * We can enjoy lots of benefits by the normalized and standardized message structure used in @@ -2940,8 +4221,8 @@ declare namespace samchon.protocol { * like a object (class) in OOD. And those relationships can be easily designed by using design * pattern.

    * - *

    In Samchon Framework, you can make any type of network system with basic 3 + 1 componenets - * (IProtocol, IServer and IClient + ServerConnector), by implemens or inherits them, like designing + *

    In Samchon Framework, you can make any type of network system with basic componenets + * (IProtocol, IServer and ICommunicator) by implemens or inherits them, like designing * classes of S/W architecture.

    * * @see IProtocol @@ -2952,6 +4233,10 @@ declare namespace samchon.protocol { *

    Listener, represent function's name.

    */ protected listener: string; + /** + * Default Constructor. + */ + constructor(); constructor(listener: string); /** * Copy Constructor. @@ -2959,13 +4244,17 @@ declare namespace samchon.protocol { * @param invoke */ constructor(invoke: Invoke); - constructor(xml: library.XML); - constructor(listener: string, begin: std.VectorIterator, end: std.VectorIterator); - constructor(listener: string, ...parameters: any[]); + /** + * Construct from listener and parametric values. + * + * @param listener + * @param parameters + */ + constructor(listener: string, ...parameters: Array); /** * @inheritdoc */ - createChild(xml: library.XML): InvokeParameter; + protected createChild(xml: library.XML): InvokeParameter; /** * Get listener. */ @@ -2990,93 +4279,10 @@ declare namespace samchon.protocol { CHILD_TAG(): string; } } -declare namespace samchon.protocol { - /** - *

    A history of an Invoke message.

    - * - *

    InvokeHistory is a class for reporting history log of an Invoke message with elapsed time - * from a slave to its master.

    - * - *

    With the elapsed time, consumed time for a process of handling the Invoke message, - * InvokeHistory is reported to the master. The master utilizies the elapsed time to estimating - * performances of each slave system. With the estimated performan index, master retrives the - * optimal solution of distributing processes.

    - * - * @author Jeongho Nam - */ - class InvokeHistory extends Entity { - /** - *

    An identifier.

    - */ - protected uid: number; - /** - *

    A listener of the Invoke message.

    - * - *

    InvokeHistory does not archive entire data of an Invoke message. InvokeHistory only - * archives its listener. The first, formal reason is to save space, avoid wasting spaces.

    - * - *

    The second, complicate reason is on an aspect of which systems are using the - * InvokeHistory class. InvokeHistory is designed to let slave reports to master elapsed time - * of a process used to handling the Invoke message. If you want to archive entire history log - * of Invoke messages, then the subject should be master, not the slave using InvokeHistory - * classes.

    - */ - protected listener: string; - /** - *

    Start time of the history.

    - * - *

    Means start time of a process handling the Invoke message. The start time not only - * has ordinary arguments represented Datetime (year to seconds), but also has very precise - * values under seconds, which is expressed as nano seconds (10^-9).

    - * - *

    The precise start time will be used to calculate elapsed time with end time.

    - */ - protected startTime: Date; - /** - *

    End time of the history.

    - * - * @details - *

    Means end time of a process handling the Invoke message. The end time not only - * has ordinary arguments represented Datetime (year to seconds), but also has very precise - * values under seconds, which is expressed as nano seconds (10^-9).

    - * - *

    The precise end time will be used to calculate elapsed time with start time.

    - */ - protected endTime: Date; - /** - *

    Construct from an Invoke message.

    - * - *

    InvokeHistory does not archive entire Invoke message, only archives its listener.

    - * - * @param invoke A message to archive its history log - */ - constructor(invoke: Invoke); - /** - *

    Notify end of the process.

    - * - *

    Notifies end of a process handling the matched Invoke message to InvokeHistory.

    - *

    InvokeHistory archives the end datetime and calculates elapsed time as nanoseconds.

    - */ - notifyEnd(): void; - TAG(): string; - toXML(): library.XML; - /** - *

    Get an Invoke message.

    - * - *

    Returns an Invoke message to report to a master that how much time was elapsed on a - * process handling the Invoke message. In master, those reports are used to estimate - * performance of each slave system.

    - * - * @return An Invoke message to report master. - */ - toInvoke(): Invoke; - } -} declare namespace samchon.protocol { /** * A parameter belongs to an Invoke. * - * @see Invoke * @author Jeongho Nam */ class InvokeParameter extends Entity { @@ -3093,31 +4299,33 @@ declare namespace samchon.protocol { /** *

    Value of the parameter.

    */ - protected value: any; + protected value: string | number | library.XML | Uint8Array; /** * Default Constructor. */ constructor(); + constructor(val: number); + constructor(val: string); + constructor(val: library.XML); + constructor(val: Uint8Array); /** - * Initialization Constructor without type specification. + * Construct from variable name and number value. * * @param name * @param val */ - constructor(name: string, val: any); - /** - * Initialization Constructor. - * - * @param name - * @param type - * @param val - */ - constructor(name: string, type: string, val: any); + constructor(name: string, val: number); + constructor(name: string, val: string); + constructor(name: string, val: library.XML); + constructor(name: string, val: Uint8Array); /** * @inheritdoc */ construct(xml: library.XML): void; - setValue(value: any): void; + setValue(value: number): any; + setValue(value: string): any; + setValue(value: library.XML): any; + setValue(value: Uint8Array): any; /** * @inheritdoc */ @@ -3145,193 +4353,1781 @@ declare namespace samchon.protocol { } } declare namespace samchon.protocol { - /** - *

    A server connector for a physical client.

    - * - *

    ServerConnector is a class for a physical client connecting a server. If you want to connect - * to a server, then implements this ServerConnector and just override some methods like - * getIP(), getPort() and replyData(). That's all.

    - * - *

    In Samchon Framework, package protocol, There are basic 3 + 1 components that can make any - * type of network system in Samchon Framework. The basic 3 components are IProtocol, IServer and - * IClient. The last, surplus one is the ServerConnector. Looking around classes in - * Samchon Framework, especially module master and slave which are designed for realizing - * distributed processing systems and parallel processing systems, physical client classes are all - * derived from this ServerConnector.

    - * - * - * - * @author Jeongho Nam - */ - class ServerConnector implements IProtocol { + class InvokeHistory extends Entity { /** - *

    A parent object who listens and sends Invoke message.

    * - *
      - *
    • ServerConnector.replyData(Invoke) -> parent.replyData(Invoke)
    • - *
    */ - private parent; + private uid; /** - *

    A socket for network I/O.

    + * @see {@link Invoke.listener} */ - private socket; - private binary_invoke; + private listener; /** - *

    An open-event listener.

    - */ - onopen: Function; - /** - *

    Constructor with parent.

    - */ - constructor(parent: IProtocol); - /** - *

    Connects to a cloud server with specified host and port.

    * - *

    If the connection fails immediately, either an event is dispatched or an exception is thrown: - * an error event is dispatched if a host was specified, and an exception is thrown if no host - * was specified. Otherwise, the status of the connection is reported by an event. - * If the socket is already connected, the existing connection is closed first.

    + */ + private startTime; + /** * - * @param ip - * The name or IP address of the host to connect to. - * If no host is specified, the host that is contacted is the host where the calling - * file resides. If you do not specify a host, use an event listener to determine whether - * the connection was successful. - * @param port - * The port number to connect to. - * - * @throws IOError - * No host was specified and the connection failed. - * @throws SecurityError - * This error occurs in SWF content for the following reasons: - * Local untrusted SWF files may not communicate with the Internet. You can work around - * this limitation by reclassifying the file as local-with-networking or as trusted. */ - connect(ip: string, port: number, path?: string): void; + private endTime; /** - *

    Send data to the server.

    + * Default Constructor. */ - sendData(invoke: Invoke): void; - /** - *

    Shift responsiblity of handling message to parent.

    - */ - replyData(invoke: Invoke): void; - private handleConnect(event); - /** - *

    Handling replied message.

    - */ - private handleReply(event); + constructor(); + constructor(invoke: Invoke); + construct(xml: library.XML): void; + notifyEnd(): void; + key(): number; + getUID(): number; + getListener(): string; + getStartTime(): Date; + getEndTime(): Date; + computeElapsedTime(): number; + TAG(): string; + toXML(): library.XML; + toInvoke(): Invoke; } } -declare namespace samchon.protocol.service { +declare namespace samchon.protocol { /** - *

    An application, the top class in JS-UI.

    + *

    An interface for a physical server.

    + * + *

    {@link IServer} provides methods for opening a server. Extends one of them who are derived from this + * {@link IServer} and open the server with method {@link open IServer.open()}. Override + * {@link addClient IServer.addClient()} who accepts a newly connected client with {@link IClientDriver}. + * If you're embarrased because your class already extended another one, then use {@link IServerBase}.

    * - *

    The Application is separated to three part, TopMenu, Movie and ServerConnector.

    *
      - *
    • TopMenu: Menu on the top. It's not an essential component.
    • - *
    • Movie: Correspond with Service in Server. Movie has domain UI components(Movie) for the matched Service.
    • - *
    • ServerConnector: The socket connecting to the Server.
    • + *
    • {@link Server}
    • + *
    • {@link WebServer}
    • + *
    • {@link SharedWorkerServer}
    • *
    * - *

    The Application and its UI-layout is not fixed, essential component for Samchon Framework in Flex, - * so it's okay to do not use the provided Application and make your custom Application. - * But the custom Application, your own, has to contain the Movie and keep the construction routine.

    + *

    + * + *

    * - *

    + *

    Basic Components

    + *

    What Basic Components are

    + *

    Basic Components are the smallest unit of network communication in this Samchon Framework. With + * Basic Components, you can construct any type of network system, even how the network system is enormously + * scaled and complicated, by just combinating the Basic Components.

    + * + *

    All the system templates in this framework are also being implemented by utilization of the + * Basic Compoonents.

    * - *

    THE CONSTRUCTION ROUTINE

    *
      - *
    • Socket Connection
    • - *
        - *
      • Connect to the CPP-Server
      • - *
      - *
    • Fetch authority
    • - *
        - *
      • Send a request to fetching authority
      • - *
      • The window can be navigated to other page by the authority
      • - *
      - *
    • Construct Movie
    • - *
        - *
      • Determine a Movie by URLVariables::movie and construct it
      • - *
      - *
    • All the routines are done
    • + *
    • {@link service Service} + *
    • {@link external External System} + *
    • {@link parallel Parallel System} + *
    • {@link distributed Distributed System} *
    * + *

    Note that, whatever the network system what you've to construct is, just concentrate on role of each system + * and attach matched Basic Components to the role, within framework of the Object-Oriented Design. + * Then construction of the network system will be much easier.

    + * + *
      + *
    • A system is a server, then use {@link IServer} or {@link IServerBase}.
    • + *
    • A server wants to handle a client has connected, then use {@link IClientDriver}.
    • + *
    • A system is a client connecting to an external server, then use {@link IServerConnector}.
    • + *
    • + *
    + * + *

    Example - System Templates

    + *

    Learning and understanding Basic Components of Samchon Framework, reading source codes and design of + * System Templates' modules will be very helpful.

    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Name Source API Documents
    Cloud Service protocol/service {@link protocol.service}
    External System protocol/external {@link protocol.external}
    Parallel System protocol/parallel {@link protocol.parallel}
    Distributed System protocol/distributed {@link protocol.distributed}
    Slave System protocol/slave {@link protocol.slave}
    + * + *

    Example - Projects

    + * + * + * @see {@link IClientDriver} + * @handbook Basic Components - IServer * @author Jeongho Nam */ - class Application implements IProtocol { - /** - *

    Invoke Socket.

    - */ - protected socket: ServerConnector; - /** - *

    A movie.

    - */ - protected movie: Movie; - /** - *

    Construct from arguments.

    - * - * @param movie A movie represents a service. - * @param ip An ip address of cloud server to connect. - * @param port A port number of cloud server to connect. - */ - constructor(movie: Movie, ip: string, port: number); - private handleConnect(event); - /** - *

    Handle replied message or shift the responsibility.

    - */ - replyData(invoke: Invoke): void; - /** - *

    Send a data to server.

    - */ - sendData(invoke: Invoke): void; + interface IServer { + open(port: number): void; + close(): void; + addClient(clientDriver: IClientDriver): void; } } -declare namespace samchon.protocol.service { - /** - * A movie belonged to an Application. - */ - class Movie implements IProtocol { +declare namespace samchon.protocol { + abstract class Server implements IServer { + private server; /** - *

    An application the movie is belonged to + * @inheritdoc */ - protected application: Application; + abstract addClient(driver: ClientDriver): void; /** - * Handle replied data. + * @inheritdoc */ - replyData(invoke: Invoke): void; + open(port: number): void; /** - * Send data to server. + * @inheritdoc */ - sendData(invoke: Invoke): void; + close(): void; + private handle_connect(socket); } } -declare namespace samchon.protocol.service { -} -declare namespace samchon.protocol.slave { - /** - * @brief A slave system. - * - * @details - *

    SlaveSystem, literally, means a slave system belongs to a maste system.

    - * - *

    The SlaveSystem class is used in opposite side system of master::DistributedSystem - * and master::ParallelSystem and reports elapsed time of each commmand (by Invoke message) - * for estimation of its performance.

    - * - * @inheritdoc - * @author Jeongho Nam - */ - abstract class SlaveSystem extends ExternalSystem { +declare namespace samchon.protocol { + abstract class WebServer implements IServer { /** - *

    Default Constructor.

    + * A server handler. + */ + private http_server; + /** + * Sequence number for issuing session id. + */ + private sequence; + /** + * @hidden + */ + private my_port; + /** + * Default Constructor. */ constructor(); /** * @inheritdoc */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + abstract addClient(driver: WebClientDriver): void; + /** + *

    Handle request from a client system.

    + * + *

    This method {@link handle_request} will be called when a client is connected. It will call an abstract + * method method {@link addClient addClient()} who handles an accepted client. If the newly connected client + * doesn't have its own session id, then a new session id will be issued.

    + * + * @param request Requested header. + */ + private handle_request(request); + /** + *

    Get session id from a newly connected.

    + * + *

    Queries ordinary session id from cookies of a newly connected client. If the client has not, a new + * session id will be issued.

    + * + * @param cookies Cookies from the remote client. + */ + private get_session_id(cookies); + /** + * Issue a new session id. + */ + private issue_session_id(); + } +} +declare namespace samchon.protocol { + abstract class SharedWorkerServer implements IServer { + /** + * @inheritdoc + */ + abstract addClient(driver: SharedWorkerClientDriver): void; + /** + * @inheritdoc + */ + open(): void; + /** + * @inheritdoc + */ + close(): void; + private handle_connect(event); + } +} +declare namespace samchon.protocol { + /** + *

    An interface for substitute server classes.

    + * + *

    {@link IServerBase} is an interface for substitue server classes who subrogate server's role.

    + * + *

    The easiest way to defining a server class is to extending one of them, who are derived from the + * {@link IServer}.

    + * + *
      + *
    • {@link Server}
    • + *
    • {@link WebServer}
    • + *
    • {@link SharedWorkerServer}
    • + *
    + * + *

    However, it is impossible (that is, if the class is already extending another class), you can instead implement + * the {@link IServer} interface, create an {@link IServerBase} member, and write simple hooks to route calls into the + * aggregated {@link IServerBase}.

    + * + *

    {@link ExternalClientArray} can be a good example using this {@link IServerBase}.

    + *
      + *
    • https://github.com/samchon/framework/blob/master/ts/src/samchon/protocol/external/ExternalClientArray.ts
    • + *
    + * + * + class MyServer extends Something implements IServer + { + private server_base: IServerBase = new WebServerBase(this); + + public addClient(driver: IClientDriver): void + { + // WHAT TO DO WHEN A CLIENT HAS CONNECTED + } + + public open(port: number): void + { + this.server_base.open(); + } + public close(): void + { + this.server_base.close(); + } + } + * + * + * @see {@link IServer} + * @handbook Basic Components - IServerBase + * @author Jeongho Nam + */ + interface IServerBase extends IServer { + } +} +declare namespace samchon.protocol { + /** + *

    A substitute {@link Server}.

    + * + *

    {@link ServerBase} is a substitute class who subrogates {@link Server}'s responsibility.

    + * + *

    The easiest way to defning a server class following normal protocol of Samchon Framework is to extending + * {@link Server}. However, it is impossible (that is, if the class is already extending another class), you can + * instead implement the {@link IServer} interface, create a {@link ServerBase} member, and write simple hooks + * to route calls into the aggregated {@link ServerBase}.

    + * + *

    {@link ExternalClientArray} can be a good example using this {@link IServerBase}.

    + *
      + *
    • https://github.com/samchon/framework/blob/master/ts/src/samchon/protocol/external/ExternalClientArray.ts
    • + *
    + * + * + class MyServer extends Something implements IServer + { + private server_base: ServerBase = new ServerBase(this); + + public addClient(driver: ClientDriver): void + { + // WHAT TO DO WHEN A CLIENT HAS CONNECTED + } + + public open(port: number): void + { + this.server_base.open(); + } + public close(): void + { + this.server_base.close(); + } + } + * + * + * @author Jeongho Nam + */ + class ServerBase extends Server implements IServerBase { + private target; + constructor(target: IServer); + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + *

    A substitute {@link WebServer}.

    + * + *

    {@link WebServerBase} is a substitute class who subrogates {@link WebServer}'s responsibility.

    + * + *

    The easiest way to defning a server class following normal protocol of Samchon Framework is to extending + * {@link WebServer}. However, it is impossible (that is, if the class is already extending another class), you can + * instead implement the {@link IServer} interface, create a {@link WebServerBase} member, and write simple hooks to + * route calls into the aggregated {@link WebServerBase}.

    + * + *

    {@link ExternalClientArray} can be a good example using this {@link IServerBase}.

    + *
      + *
    • https://github.com/samchon/framework/blob/master/ts/src/samchon/protocol/external/ExternalClientArray.ts
    • + *
    + * + * + class MyServer extends Something implements IServer + { + private server_base: WebServerBase = new WebServerBase(this); + + public addClient(driver: WebClientDriver): void + { + // WHAT TO DO WHEN A CLIENT HAS CONNECTED + } + + public open(port: number): void + { + this.server_base.open(); + } + public close(): void + { + this.server_base.close(); + } + } + * + * + * @author Jeongho Nam + */ + class WebServerBase extends WebServer implements IServerBase { + private target; + constructor(target: IServer); + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + *

    A substitute {@link SharedWorkerServer}.

    + * + *

    {@link SharedWorkerServerBase} is a substitute class who subrogates {@link SharedWorkerServer}'s + * responsibility.

    + * + *

    The easiest way to defning a server class following normal protocol of Samchon Framework is to extending + * {@link SharedWorkerServer}. However, it is impossible (that is, if the class is already extending another class), + * you can instead implement the {@link IServer} interface, create a {@link SharedWorkerServerBase} member, and write + * simple hooks to route calls into the aggregated {@link SharedWorkerServerBase}.

    + * + *

    {@link ExternalClientArray} can be a good example using this {@link IServerBase}.

    + *
      + *
    • https://github.com/samchon/framework/blob/master/ts/src/samchon/protocol/external/ExternalClientArray.ts
    • + *
    + * + * + class MyServer extends Something implements IServer + { + private server_base: SharedWorkerServerBase = new SharedWorkerServerBase(this); + + public addClient(driver: SharedWorkerClientDriver): void + { + // WHAT TO DO WHEN A CLIENT HAS CONNECTED + } + + public open(port: number): void + { + this.server_base.open(); + } + public close(): void + { + this.server_base.close(); + } + } + * + * + * @author Jeongho Nam + */ + class SharedWorkerServerBase extends SharedWorkerServer implements IServerBase { + private target; + constructor(target: IServer); + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + *

    An interface for server connector.

    + * + *

    {@link IServerConnector} is an interface for server connector classes who ca connect to an external server + * as a client.

    + * + *

    Of course, {@link IServerConnector} is extended from the {@link ICommunicator}, thus, it also takes full + * charge of network communication and delivers replied message to {@link WebCommunicator.listener listener}'s + * {@link IProtocol.replyData replyData()} method.

    + * + * @handbook Basic Components - IServerConnector + * @author Jeongho Nam + */ + interface IServerConnector extends ICommunicator { + /** + * Callback function for connection completed. + */ + onConnect: Function; + /** + *

    Connect to a server.

    + * + *

    Connects to a server with specified host address and port number. After the connection has + * succeeded, callback function {@link onConnect} is called. Listening data from the connected server also begins. + * Replied messages from the connected server will be converted to {@link Invoke} classes and will be shifted to + * the {@link WebCommunicator.listener listener}'s {@link IProtocol.replyData replyData()} method.

    + * + *

    If the connection fails immediately, either an event is dispatched or an exception is thrown: an error + * event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, + * the status of the connection is reported by an event. If the socket is already connected, the existing + * connection is closed first.

    + * + * @param ip The name or IP address of the host to connect to. + * If no host is specified, the host that is contacted is the host where the calling file resides. + * If you do not specify a host, use an event listener to determine whether the connection was + * successful. + * @param port The port number to connect to. + */ + connect(ip: string, port: number): void; + } +} +declare namespace samchon.protocol { + class ServerConnector extends Communicator implements IServerConnector { + /** + * @inheritdoc + */ + onConnect: Function; + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + connect(ip: string, port: number): void; + private handle_connect(...arg); + } +} +declare namespace samchon.protocol { + /** + *

    A server connector for web-socket protocol.

    + * + * @author Jeongho Nam + */ + class WebServerConnector extends WebCommunicator implements IServerConnector { + /** + *

    A socket for network I/O.

    + * + *

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

    + */ + private browser_socket; + /** + *

    A driver for server connection.

    + * + *

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

    + */ + private node_client; + /** + * @inheritdoc + */ + onConnect: Function; + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + connect(ip: string, port: number, path?: string): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + private handle_browser_connect(event); + private handle_browser_message(event); + private handle_node_connect(connection); + } +} +declare namespace samchon.protocol { + class SharedWorkerServerConnector extends SharedWorkerCommunicator implements IServerConnector { + /** + * @inheritdoc + */ + onConnect: Function; + constructor(listener: IProtocol); + connect(jsFile: string): void; + } +} +declare namespace samchon.protocol { + namespace socket { + type socket = any; + type server = any; + type http_server = any; + } + namespace websocket { + type connection = any; + type request = any; + type IMessage = any; + type ICookie = any; + type client = any; + } +} +declare namespace samchon.protocol.external { + /** + *

    An external system driver.

    + * + *

    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.

    + * + *

    + * + *

    + * + *

    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 + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.

    + * + *
      + *
    • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
    • + *
    • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
    • + *
    • Those strategy is called Bridge Pattern and Proxy Pattern.
    • + *
    + * + * @author Jeongho Nam + */ + abstract class ExternalSystem extends EntityDequeCollection implements IProtocol { + /** + * A network communicator with external system. + */ + /** + * A network communicator with external system. + */ + protected communicator: ICommunicator; + /** + * The name represents external system have connected. + */ + protected name: string; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from an IClientDriver object. + * + * @param driver + */ + constructor(driver: IClientDriver); + /** + * Default Destructor. + */ + destructor(): void; + /** + * Identifier of {@link ExternalSystem} is its {@link name}. + */ + key(): string; + /** + * Get {@link name}. + */ + getName(): string; + close(): void; + /** + * Send {@link Invoke} message to external system. + * + * @param invoke An {@link Invoke} message to send. + */ + sendData(invoke: Invoke): void; + /** + * Handle an {@Invoke} message have received. + * + * @param invoke An {@link Invoke} message have received. + */ + 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}. + * + * @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); + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedSystem extends parallel.ParallelSystem { + } +} +declare namespace samchon.protocol.external { + /** + *

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

    + * + *

    {@link ExternalSystemArray} is an abstract class contains and manages external system drivers, + * {@link ExternalSystem} objects. You can specify this {@link ExternalSystemArray} to be a server accepting + * {@link ExternalSystem external clients} or a client connecting to {@link IExternalServer external servers}. Even + * both of them is also possible.

    + * + *
      + *
    • A server accepting external clients: {@link IExternalClientArray}
    • + *
    • A client connecting to external servers: {@link IExternalServerArray}
    • + *
    • + * Accepts external clients & Connects to external servers at the same time: + * {@link IExternalServerClientArray} + *
    • + *
    + * + *

    + * + *

    + * + *

    Proxy Pattern

    + *

    The {@link ExternalSystemArray} class can use Proxy Pattern. 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 + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.

    + * + *
      + *
    • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
    • + *
    • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
    • + *
    • Those strategy is called Proxy Pattern.
    • + *
    + * + * @author Jeongho Nam + */ + abstract class ExternalSystemArray extends EntityArrayCollection 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. + * + * @param name Name, identifier of target {@link ExternalSystemRole role}. + * + * @return Whether the role has or not. + */ + hasRole(name: string): boolean; + /** + * Get a role. + * + * @param name Name, identifier of target {@link ExternalSystemRole role}. + * + * @return The specified role. + */ + getRole(name: string): ExternalSystemRole; + /** + *

    Send an {@link Invoke} message.

    + * + * @param invoke An {@link Invoke} message to send. + */ + sendData(invoke: Invoke): void; + /** + *

    Handle an {@Invoke} message have received.

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

    A manager containing {@link ParallelSystem} objects.

    + * + * + * + * @author Jeongho Nam + */ + abstract class ParallelSystemArray extends external.ExternalSystemArray { + /** + * @see {@link ParallelSystem.progress_list}, {@link ParallelSystem.history_list} + */ + private history_sequence; + /** + * Default Constructor. + */ + constructor(); + /** + * + * @param invoke An invoke message requesting parallel process. + * @param size Number of pieces. + */ + sendSegmentData(invoke: Invoke, size: number): void; + /** + * + * + * @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. + */ + sendPieceData(invoke: Invoke, first: number, last: number): void; + /** + * + * @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; + /** + * @see {@link ParallelSystem.performance} + */ + private normalize_performance(); + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedSystemArray extends parallel.ParallelSystemArray { + protected roles: std.HashMap; + } +} +declare namespace samchon.protocol.external { + /** + *

    A role of an external system.

    + * + *

    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.

    + * + *

    + * + *

    + * + *

    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 + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.

    + * + *
      + *
    • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
    • + *
    • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
    • + *
    • Those strategy is called Proxy Pattern.
    • + *
    + * + * @author Jeongho Nam + */ + abstract class ExternalSystemRole extends Entity implements IProtocol { + /** + * An {@link ExternalSystem external system} containing this {@link ExternalSystemRole role}. + */ + private system; + /** + *

    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}. + */ + private name; + /** + * Constructor from a system. + * + * @param system An external system containing this role. + */ + constructor(system: ExternalSystem); + /** + * Identifier of {@link ExternalSystemRole} is its {@link name}. + */ + key(): string; + /** + * Get external system, this role is belonged to. + */ + getSystem(): ExternalSystem; + /** + * Get name, who represents and identifies this role. + */ + getName(): string; + /** + * Send an {@link Invoke} message to the external system via {@link system}. + * + * @param invoke An {@link Invoke} message to send to the external system. + */ + sendData(invoke: Invoke): void; + /** + *

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

    + * + *

    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 ExternalSytemRole} in {@link XML}. + * + * @return role. + */ + TAG(): string; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedSystemRole extends external.ExternalSystemRole { + private systems; + } +} +declare namespace samchon.protocol.external { + /** + *

    An interface for an {@link ExternalSystemArray} accepts {@link ExternalSystem external clients} as a + * {@link IServer server}.

    + * + *

    The easiest way to defining an {@link ExternalSystemArray} who opens server and accepts + * {@link ExternalSystem external clients} is to extending one of below, who are derived from this interface + * {@link IExternalClientArray}. However, if you can't specify an {@link ExternalSystemArray} to be whether server or + * client, then make a class (let's name it as BaseSystemArray) extending {@link ExternalSystemArray} and make + * a new class (now, I name it BaseClientArray) extending BaseSystemArray and implementing this + * interface {@link IExternalClientArray}. Define the BaseClientArray following those codes on below: + * + *

    + * + * @author Jeongho Nam + */ + interface IExternalClientArray extends ExternalSystemArray, IServer { + } + /** + *

    An {@link ExternalSystemArray} acceepts {@link ExternalSystem external clients} as a {@link IServer server}.

    + * + *

    {@link ExternalServerArray} is an abstract class contains, manages and accepts external server drivers, + * {@link IExternalServer} objects, as a {@link IServer server}.

    + * + *

    + * + *

    + * + *

    Proxy Pattern

    + *

    The {@link ExternalSystemArray} class can use Proxy Pattern. 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 + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.

    + * + *
      + *
    • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
    • + *
    • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
    • + *
    • Those strategy is called Proxy Pattern.
    • + *
    + * + * @author Jeongho Nam + */ + abstract class ExternalClientArray extends ExternalSystemArray implements 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; + /** + * This method is deprecated. Don't use and override this. + * + * @return null. + */ + protected createChild(xml: library.XML): ExternalSystem; + /** + * Factory method creating {@link ExternalSystem} object. + * + * @param driver A communicator with connected client. + * @return A newly created {@link ExternalSystem} object. + */ + protected abstract createExternalClient(driver: IClientDriver): ExternalSystem; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.protocol.external { + /** + *

    An interface for an external server driver.

    + * + *

    The easiest way to defining an external server driver is to extending one of below, who are derived from this + * interface {@link IExternalServer}. However, if you've to interact with an external system who can be both server + * and client, then make a class (let's name it as BaseSystem) extending {@link ExternalSystem} and make a + * new class (now, I name it BaseServer) extending BaseSystem and implementing this interface + * {@link IExternalServer}. Define the BaseServer following those codes on below: + * + *

    + * + * @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.

    + * + *

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

    + * + *

    + * + *

    + * + *

    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 + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.

    + * + *
      + *
    • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
    • + *
    • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
    • + *
    • Those strategy is called Bridge Pattern and Proxy Pattern.
    • + *
    + * + * @author Jeongho Nam + */ + abstract class ExternalServer extends ExternalSystem implements IExternalServer { + /** + * IP address of target external system to connect. + */ + protected ip: string; + /** + * Port number of target external system to connect. + */ + protected port: number; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating server connector. + */ + protected abstract createServerConnector(): IServerConnector; + /** + * @inheritdoc + */ + connect(): void; + /** + * @inheritdoc + */ + getIP(): string; + /** + * @inheritdoc + */ + getPort(): number; + } +} +declare namespace samchon.protocol.external { + /** + *

    An interface for an {@link ExternalSystemArray} connects to {@link IExternalServer external servers} as a + * client.

    + * + *

    The easiest way to defining an {@link ExternalSystemArray} who connects to + * {@link IExternalServer external servers} is to extending one of below, who are derived from this interface + * {@link IExternalServerArray}. However, if you can't specify an {@link ExternalSystemArray} to be whether server or + * client, then make a class (let's name it as BaseSystemArray) extending {@link ExternalSystemArray} and make + * a new class (now, I name it BaseServerArray) extending BaseSystemArray and implementing this + * interface {@link IExternalServerArray}. Define the BaseServerArray following those codes on below: + * + *

    + * + * @author Jeongho Nam + */ + interface IExternalServerArray extends ExternalSystemArray { + /** + *

    Connect to {@link IExternalServer external servers}.

    + * + *

    This method calls children elements' method {@link IExternalServer.connect} gradually.

    + */ + connect(): void; + } + /** + *

    An {@link ExternalSystemArray} connecting to {@link IExternalServer external servers} as a client.

    + * + *

    {@link ExternalServerArray} is an abstract class contains, manages and connects to external server drivers, + * {@link IExternalServer} objects, as a client.

    + * + *

    + * + *

    + * + *

    Proxy Pattern

    + *

    The {@link ExternalSystemArray} class can use Proxy Pattern. 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 + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.

    + * + *
      + *
    • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
    • + *
    • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
    • + *
    • Those strategy is called Proxy Pattern.
    • + *
    + * + * @author Jeongho Nam + */ + abstract class ExternalServerArray extends ExternalSystemArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.protocol.external { + /** + *

    An interface for an {@link ExternalSystemArray} accepts {@link ExternalSystem external clients} as a + * {@link IServer server} and connects to {@link IExternalServer} as client, at the same time.

    + * + *

    The easiest way to defining an {@link IExternalServerClientArray} who opens server, accepts + * {@link ExternalSystem external clients} and connects to {@link IExternalServer external servers} is to extending + * one of below, who are derived from this interface {@link IExternalServerClientArray}. However, if you can't + * specify an {@link ExternalSystemArray} to be whether server or client or even can both them, then make a class + * (let's name it as BaseSystemArray) extending {@link ExternalSystemArray} and make a new class (now, I name + * it BaseServerClientArray) extending BaseSystemArray and implementing this interface + * {@link IExternalServerClientArray}. Define the BaseServerClientArray following those codes on below: + * + *

    + * + * @author Jeongho Nam + */ + interface IExternalServerClientArray extends IExternalServerArray, IExternalClientArray { + } + /** + *

    An {@link ExternalSystemArray} connecting to {@link IExternalServer external servers} as a client and + * accepts {@link ExternalSystem external clients} as a {@link IServer server}.

    + * + *

    {@link ExternalServerArray} is an abstract class contains, manages and connects to external server drivers, + * {@link IExternalServer} objects and accepts external client drivers {@link ExternalSyste} obejcts as a + * client and a {@link IServer server} at the same time.

    + * + *

    + * + *

    + * + *

    Proxy Pattern

    + *

    The {@link ExternalSystemArray} class can use Proxy Pattern. 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 + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.

    + * + *
      + *
    • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
    • + *
    • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
    • + *
    • Those strategy is called Proxy Pattern.
    • + *
    + * + * @author Jeongho Nam + */ + abstract class ExternalServerClientArray extends ExternalClientArray implements IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + *

    Factory method of a child Entity.

    + * + *

    This method is migrated to {@link createExternalServer createExternalServer()}. Override the + * {@link createExternalServer createExternalServer()}.

    + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * + * @return A new child Entity via {@link createExternalServer createExternalServer()}. + */ + protected createChild(xml: library.XML): ExternalSystem; + /** + * Factory method creating an {@link IExternalServer} object. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * + * @return A newly created {@link IExternalServer} object. + */ + protected abstract createExternalServer(xml: library.XML): IExternalServer; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.protocol.slave { + abstract class SlaveSystem extends external.ExternalSystem { + /** + * Default Constructor. + */ + constructor(); replyData(invoke: Invoke): void; } } +declare namespace samchon.protocol.external { + abstract class MediatorSystem extends slave.SlaveSystem { + private system_array; + private progress_list; + constructor(systemArray: ExternalSystemArray); + abstract start(): void; + /** + * @hidden + */ + protected createChild(xml: library.XML): ExternalSystemRole; + private notify_end(uid); + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.protocol.external { + class MediatorServer extends MediatorSystem implements IServer { + private server_base; + private port; + constructor(systemArray: ExternalSystemArray, port: number); + protected createServerBase(): IServerBase; + addClient(driver: IClientDriver): void; + start(): void; + open(port: number): void; + close(): void; + } + class MediatorWebServer extends MediatorServer { + protected createServerBase(): IServerBase; + } + class MediatorSharedWorkerServer extends MediatorServer { + protected createServerBase(): IServerBase; + } +} +declare namespace samchon.protocol.external { + class MediatorClient extends MediatorSystem implements IExternalServer { + protected ip: string; + protected port: number; + constructor(systemArray: ExternalSystemArray, ip: string, port: number); + protected createServerConnector(): IServerConnector; + getIP(): string; + getPort(): number; + start(): void; + connect(): void; + } + class MediatorWebClient extends MediatorClient { + /** + * @inheritdoc + */ + protected createServerConnector(): IServerConnector; + } + class MediatorSharedWorkerClient extends MediatorClient { + /** + * @inheritdoc + */ + protected createServerConnector(): IServerConnector; + } +} +declare namespace samchon.protocol.parallel { + class PRInvokeHistory extends InvokeHistory { + /** + * Index number of initial piece. + */ + private first; + /** + * Index number of final piece. + */ + private last; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from an Invoke message. + * + * @param invoke + */ + constructor(invoke: Invoke); + getFirst(): number; + getLast(): number; + /** + * Compute number of allocated pieces. + */ + computeSize(): number; + } +} +declare namespace samchon.protocol.parallel { + abstract class ParallelClientArray extends ParallelSystemArray 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; + protected createChild(xml: library.XML): ParallelSystem; + protected abstract createExternalClient(driver: IClientDriver): ParallelSystem; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.protocol.parallel { + abstract class ParallelSystemArrayMediator extends ParallelSystemArray { + protected mediator: external.MediatorSystem; + /** + * Default Constructor. + */ + constructor(); + protected abstract createMediator(): external.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; + } +} +declare namespace samchon.protocol.parallel { + abstract class ParallelClientArrayMediator extends ParallelSystemArrayMediator 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; + protected createChild(xml: library.XML): ParallelSystem; + protected abstract createExternalClient(driver: IClientDriver): ParallelSystem; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.protocol.parallel { + interface IParallelServer extends ParallelSystem, external.IExternalServer { + } + abstract class ParallelServer extends ParallelSystem implements IParallelServer { + protected ip: string; + protected port: number; + constructor(systemArray: ParallelSystemArray); + protected abstract createServerConnector(): IServerConnector; + connect(): void; + getIP(): string; + getPort(): number; + } +} +declare namespace samchon.protocol.parallel { + abstract class ParallelServerArray extends ParallelSystemArray implements external.IExternalServerArray { + constructor(); + connect(): void; + } +} +declare namespace samchon.protocol.parallel { + abstract class ParallelServerArrayMediator extends ParallelSystemArrayMediator implements external.IExternalServerArray { + constructor(); + connect(): void; + } +} +declare namespace samchon.protocol.parallel { + abstract class ParallelServerClientArray extends ParallelClientArray implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + protected createChild(xml: library.XML): ParallelSystem; + protected abstract createExternalServer(xml: library.XML): IParallelServer; + connect(): void; + } +} +declare namespace samchon.protocol.parallel { + abstract class ParallelServerClientArrayMediator extends ParallelClientArrayMediator implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + protected createChild(xml: library.XML): ParallelSystem; + protected abstract createExternalServer(xml: library.XML): IParallelServer; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.protocol.service { + abstract class Client implements protocol.IProtocol { + private user; + private service; + private driver; + private no; + /** + * Construct from an User and WebClientDriver. + */ + constructor(user: User, driver: WebClientDriver); + protected abstract createService(path: string): Service; + close(): void; + getUser(): User; + getService(): Service; + sendData(invoke: protocol.Invoke): void; + replyData(invoke: protocol.Invoke): void; + protected changeService(path: string): void; + } +} +declare namespace samchon.protocol.service { + abstract class Server extends protocol.WebServer implements IProtocol { + private session_map; + private account_map; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link User} object. + * + * @return A newly created {@link User} object. + */ + protected abstract createUser(): User; + has(account: string): boolean; + get(account: string): User; + sendData(invoke: protocol.Invoke): void; + replyData(invoke: protocol.Invoke): void; + addClient(driver: WebClientDriver): void; + private erase_user(user); + } +} +declare namespace samchon.protocol.service { + abstract class Service implements protocol.IProtocol { + private client; + private path; + /** + * Default Constructor. + */ + constructor(client: Client, path: string); + destructor(): void; + /** + * Get client. + */ + getClient(): Client; + /** + * Get path. + */ + getPath(): string; + sendData(invoke: protocol.Invoke): void; + replyData(invoke: protocol.Invoke): void; + } +} +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; + /** + * Construct from a Server. + */ + constructor(server: Server); + protected abstract createClient(driver: WebClientDriver): Client; + private handle_erase_client(event); + getServer(): Server; + getAccountID(): string; + getAuthority(): number; + setAccount(id: string, authority: number): void; + sendData(invoke: protocol.Invoke): void; + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.protocol.slave { + abstract class SlaveClient extends SlaveSystem { + constructor(); + protected abstract createServerConnector(): IServerConnector; + connect(ip: string, port: number): void; + } +} +declare namespace samchon.protocol.slave { + abstract class SlaveServer extends SlaveSystem implements IServer { + private server_base; + constructor(); + protected abstract createServerBase(): IServerBase; + addClient(driver: IClientDriver): void; + open(port: number): void; + close(): void; + } +} diff --git a/typescript-stl/typescript-stl-tests.ts b/typescript-stl/typescript-stl-tests.ts index cc684cde7e..d83a9ffc5a 100644 --- a/typescript-stl/typescript-stl-tests.ts +++ b/typescript-stl/typescript-stl-tests.ts @@ -1,4 +1,4 @@ /// import std = require("typescript-stl"); -std.example.test_all(); \ No newline at end of file +console.log(std); \ No newline at end of file diff --git a/typescript-stl/typescript-stl.d.ts b/typescript-stl/typescript-stl.d.ts index a0f92b88b6..9e491ff258 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.0-rc.3 +// Type definitions for TypeScript-STL v1.0.0 // Project: https://github.com/samchon/typescript-stl // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -117,13 +117,6 @@ declare namespace std { */ declare namespace std.base { } -/** - * Examples for supporting developers who use STL library. - * - * @author Jeongho Nam - */ -declare namespace std.example { -} declare namespace std { /** *

    Apply function to range.

    @@ -2751,8 +2744,8 @@ declare namespace std.base { /** *

    An abstract container.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -2872,8 +2865,8 @@ declare namespace std { *

    There is not a single type of {@link Iterator bidirectional iterator}: {@link IContainer Each container} * may define its own specific iterator type able to iterate through it and access its elements.

    * - *

    - * + *

    + * *

    * * @reference http://www.cplusplus.com/reference/iterator/BidirectionalIterator @@ -2958,18 +2951,45 @@ declare namespace std { * first element in a range is reversed, the reversed iterator points to the element before the first element (this * would be the past-the-end element of the reversed range).

    * - *

    - * + *

    + * *

    * * @reference http://www.cplusplus.com/reference/iterator/reverse_iterator * @author Jeongho Nam */ abstract class ReverseIterator, This extends ReverseIterator> extends Iterator { + /** + * @hidden + */ protected base_: Base; + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: Base); + /** + *

    Return base iterator.

    + * + *

    Return a reference of the base iteraotr.

    + * + *

    The base iterator is an iterator of the same type as the one used to construct the {@link ReverseIterator}, + * but pointing to the element next to the one the {@link ReverseIterator} is currently pointing to + * (a {@link ReverseIterator} has always an offset of -1 with respect to its base iterator). + * + * @return A reference of the base iterator, which iterates in the opposite direction. + */ base(): Base; + /** + * @hidden + */ protected abstract create_neighbor(): This; + /** + *

    Get value of the iterator is pointing.

    + * + * @return A value of the reverse iterator. + */ value: T; /** * @inheritdoc @@ -3194,8 +3214,8 @@ declare namespace std { * the end, {@link Deque Deques} perform worse and have less consistent iterators and references than * {@link List Lists}.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -3217,66 +3237,27 @@ declare namespace std { */ class Deque extends base.Container implements base.IArrayContainer, base.IDequeContainer { /** - *

    Row size of the {@link matrix_ matrix} which contains elements.

    - * - *

    Note that the {@link ROW} affects on time complexity of accessing and inserting element. - * Accessing element is {@link ROW} times slower than ordinary {@link Vector} and inserting element - * in middle position is {@link ROW} times faster than ordinary {@link Vector}.

    - * - *

    When the {@link ROW} returns 8, time complexity of accessing element is O(8) and inserting - * element in middle position is O(N/8). ({@link Vector}'s time complexity of accessement is O(1) - * and inserting element is O(N)).

    + * @hidden */ private static ROW; /** - *

    Minimum {@link capacity}.

    - * - *

    Although a {@link Deque} has few elements, even no element is belonged to, the {@link Deque} - * keeps the minimum {@link capacity} at least.

    + * @hidden */ private static MIN_CAPACITY; /** - *

    A matrix containing elements.

    - * - *

    This {@link matrix_} is the biggest difference one between {@link Vector} and {@link Deque}. - * Its number of rows follows {@link ROW} and number of columns follows {@link get_col_size} which - * returns divide of {@link capacity} and {@link ROW}.

    - * - * By separating segment of elements (segment: row, elements in a segment: col), {@link Deque} takes - * advantage of time complexity on inserting element in middle position. {@link Deque} is {@link ROW} - * times faster than {@link Vector} when inserting elements in middle position.

    - * - *

    However, separating segment of elements from matrix, {@link Deque} also takes disadvantage of - * time complexity on accessing element. {@link Deque} is {@link ROW} times slower than {@link Vector} - * when accessing element.

    + * @hidden */ private matrix_; /** - * Number of elements in the {@link Deque}. + * @hidden */ private size_; /** - *

    Size of allocated storage capacity.

    - * - *

    The {@link capacity_ capacity} is size of the storage space currently allocated for the - * {@link Deque container}, expressed in terms of elements.

    - * - *

    This {@link capacity_ capacity} is not necessarily equal to the {@link Deque container} - * {@link size}. It can be equal or greater, with the extra space allowing to accommodate for growth - * without the need to reallocate on each insertion.

    - * - *

    Notice that this {@link capacity_ capacity} does not suppose a limit on the {@link size} of - * the {@link Deque container}. When this {@link capacity} is exhausted and more is needed, it is - * automatically expanded by the {@link Deque container} (reallocating it storage space). - * The theoretical limit on the {@link size} of a {@link Deque container} is given by member - * {@link max_size}.

    - * - *

    The {@link capacity_ capacity} of a {@link Deque container} can be explicitly altered by - * calling member {@link Deque.reserve}.

    + * @hidden */ private capacity_; /** - * Get column size; {@link capacity_ capacity} / {@link ROW row}. + * @hidden */ private get_col_size(); /** @@ -3480,8 +3461,8 @@ declare namespace std { /** *

    An iterator of {@link Deque}.

    * - *

    - * + *

    + * *

    * * @author Jeongho Nam @@ -3509,6 +3490,11 @@ declare namespace std { /** * @inheritdoc */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ value: T; /** * @inheritdoc @@ -3552,8 +3538,8 @@ declare namespace std { /** *

    A reverse-iterator of Deque.

    * - *

    - * + *

    + * *

    * * @param Type of the elements. @@ -3561,13 +3547,20 @@ declare namespace std { * @author Jeongho Nam */ class DequeReverseIterator extends ReverseIterator, DequeReverseIterator> implements base.IArrayIterator { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: DequeIterator); /** - * @inheritdoc + * @hidden */ protected create_neighbor(): DequeReverseIterator; /** - * Set value. + * Set value of the iterator is pointing to. + * + * @param val Value to set. */ value: T; /** @@ -3629,8 +3622,8 @@ declare namespace std { *

    All objects thrown by components of the standard library are derived from this class. * Therefore, all standard exceptions can be caught by catching this type by reference.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/exception/exception * @author Jeongho Nam @@ -3678,8 +3671,8 @@ declare namespace std { * *

    It is used as a base class for several logical error exceptions.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/logic_error * @author Jeongho Nam @@ -3704,8 +3697,8 @@ declare namespace std { *

    No component of the standard library throws exceptions of this type. It is designed as a standard * exception to be thrown by programs.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/domain_error * @author Jeongho Nam @@ -3726,8 +3719,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal invalid arguments.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/invalid_argument * @author Jeongho Nam @@ -3748,8 +3741,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library, * such as vector and string also throw exceptions of this type to signal errors resizing.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/length_error * @author Jeongho Nam @@ -3771,8 +3764,8 @@ declare namespace std { * such as vector, deque, string and bitset also throw exceptions of this type to signal arguments * out of range.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/out_of_range * @author Jeongho Nam @@ -3793,8 +3786,8 @@ declare namespace std { * *

    It is used as a base class for several runtime error exceptions.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/runtime_error * @author Jeongho Nam @@ -3815,8 +3808,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal range errors.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/overflow_error * @author Jeongho Nam @@ -3837,8 +3830,8 @@ declare namespace std { *

    No component of the standard library throws exceptions of this type. It is designed as a standard * exception to be thrown by programs.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/underflow_error * @author Jeongho Nam @@ -3860,8 +3853,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal range errors.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/range_error * @author Jeongho Nam @@ -4422,8 +4415,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -4820,8 +4813,8 @@ declare namespace std { /** *

    An iterator of {@link MapContainer map container}.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ @@ -4891,13 +4884,21 @@ declare namespace std { /** *

    A reverse-iterator of {@link MapContainer map container}.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ class MapReverseIterator extends ReverseIterator, MapIterator, MapReverseIterator> { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: MapIterator); + /** + * @hidden + */ protected create_neighbor(): MapReverseIterator; /** * Get first, key element. @@ -4931,8 +4932,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -5198,8 +5199,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -5311,8 +5312,8 @@ declare namespace std { *

    {@link HashMap} containers are faster than {@link TreeMap} containers to access individual elements by their * key, although they are generally less efficient for range iteration through a subset of their elements.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -5342,6 +5343,9 @@ declare namespace std { * @author Jeongho Nam */ class HashMap extends base.UniqueMap implements base.IHashMap { + /** + * @hidden + */ private hash_buckets_; /** * @hidden @@ -5473,8 +5477,8 @@ declare namespace std { *

    Elements with equivalent keys are grouped together in the same bucket and in such a way that * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -5505,7 +5509,7 @@ declare namespace std { */ class HashMultiMap extends base.MultiMap { /** - * + * @hidden */ private hash_buckets_; /** @@ -5633,8 +5637,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -5910,8 +5914,8 @@ declare namespace std { /** *

    An iterator of a Set.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ @@ -5969,146 +5973,26 @@ declare namespace std { /** *

    A reverse-iterator of Set.

    * - *

    - *

    + *

    + *

    * * @param Type of the elements. * * @author Jeongho Nam */ class SetReverseIterator extends ReverseIterator, SetReverseIterator> { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: SetIterator); /** - * @inheritdoc + * @hidden */ protected create_neighbor(): SetReverseIterator; } } -declare namespace std.base { - /** - *

    An abstract set.

    - * - *

    {@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of - * individual elements based on their value.

    - * - *

    In an {@link SetContainer}, the value of an element is at the same time its key, used to uniquely - * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be modified - * once in the container - they can be inserted and removed, though.

    - * - *

    {@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    - * - *

    - *

    - * - *

    Container properties

    - *
    - *
    Associative
    - *
    - * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
    - * - *
    Set
    - *
    The value of an element is also the key used to identify it.
    - * - *
    Unique keys
    - *
    No two elements in the container can have equivalent keys.
    - *
    - * - * @param Type of the elements. Each element in a {@link SetContainer} container is also identified - * by this value (each value is itself also the element's key). - * - * @author Jeongho Nam - */ - abstract class UniqueSet extends SetContainer { - /** - * @inheritdoc - */ - count(key: T): number; - /** - *

    Extract an element.

    - * - *

    Extracts the element pointed to by val and erases it from the {@link UniqueSet}.

    - * - * @param val Value to be extracted. - * - * @return A value. - */ - extract(val: T): T; - /** - *

    Extract an element.

    - * - *

    Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

    - * - * @param it An iterator pointing an element to extract. - * - * @return An iterator pointing to the element immediately following it prior to the element being - * erased. If no such element exists,returns {@link end end()}. - */ - extract(it: SetIterator): SetIterator; - /** - *

    Extract an element.

    - * - *

    Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

    - * - * @param it An iterator pointing an element to extract. - * - * @return An iterator pointing to the element immediately following it prior to the element being - * erased. If no such element exists,returns {@link end end()}. - */ - extract(it: SetReverseIterator): SetReverseIterator; - /** - * @hidden - */ - private extract_by_key(val); - /** - * @hidden - */ - private extract_by_iterator(it); - /** - * @hidden - */ - private extract_by_reverse_iterator(it); - /** - *

    Insert an element.

    - * - *

    Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of element inserted (zero or one).

    - * - *

    Because elements in a {@link UniqueSet UniqueSets} are unique, the insertion operation checks whether - * each inserted element is equivalent to an element already in the container, and if so, the element is not - * inserted, returning an iterator to this existing element (if the function returns a value).

    - * - *

    For a similar container allowing for duplicate elements, see {@link MultiSet}.

    - * - * @param key Value to be inserted as an element. - * - * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly - * inserted element or to the equivalent element already in the {@link UniqueSet}. The - * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or - * false if an equivalent element already existed. - */ - insert(val: T): Pair, boolean>; - /** - * @inheritdoc - */ - insert(hint: SetIterator, val: T): SetIterator; - /** - * @inheritdoc - */ - insert(hint: SetReverseIterator, val: T): SetReverseIterator; - /** - * @inheritdoc - */ - insert>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - swap(obj: UniqueSet): void; - } -} declare namespace std.base { /** *

    An abstract set.

    @@ -6124,8 +6008,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -6177,163 +6061,6 @@ declare namespace std.base { swap(obj: MultiSet): void; } } -declare namespace std.HashSet { - type iterator = std.SetIterator; - type reverse_iterator = std.SetReverseIterator; -} -declare namespace std { - /** - *

    Hashed, unordered set.

    - * - *

    {@link HashSet}s are containers that store unique elements in no particular order, and which - * allow for fast retrieval of individual elements based on their value.

    - * - *

    In an {@link HashSet}, the value of an element is at the same time its key, that - * identifies it uniquely. Keys are immutable, therefore, the elements in an {@link HashSet} cannot be - * modified once in the container - they can be inserted and removed, though.

    - * - *

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

    - * - *

    {@link HashSet} containers are faster than {@link TreeSet} containers to access individual - * elements by their key, although they are generally less efficient for range iteration through a - * subset of their elements.

    - * - *

    - *

    - * - *

    Container properties

    - *
    - *
    Associative
    - *
    Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
    - * - *
    Hashed
    - *
    Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
    - * - *
    Set
    - *
    The value of an element is also the key used to identify it.
    - * - *
    Unique keys
    - *
    No two elements in the container can have equivalent keys.
    - *
    - * - * @param Type of the elements. - * Each element in an {@link HashSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set - * @author Jeongho Nam - */ - class HashSet extends base.UniqueSet { - private hash_buckets_; - /** - * @hidden - */ - protected init(): void; - /** - * @hidden - */ - protected construct_from_array(items: Array): void; - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: T): SetIterator; - /** - * @inheritdoc - */ - begin(): SetIterator; - /** - * @inheritdoc - */ - begin(index: number): SetIterator; - /** - * @inheritdoc - */ - end(): SetIterator; - /** - * @inheritdoc - */ - end(index: number): SetIterator; - /** - * @inheritdoc - */ - rbegin(): SetReverseIterator; - /** - * @inheritdoc - */ - rbegin(index: number): SetReverseIterator; - /** - * @inheritdoc - */ - rend(): SetReverseIterator; - /** - * @inheritdoc - */ - rend(index: number): SetReverseIterator; - /** - * @inheritdoc - */ - bucket_count(): number; - /** - * @inheritdoc - */ - bucket_size(n: number): number; - /** - * @inheritdoc - */ - max_load_factor(): number; - /** - * @inheritdoc - */ - max_load_factor(z: number): void; - /** - * @inheritdoc - */ - bucket(key: T): number; - /** - * @inheritdoc - */ - reserve(n: number): void; - /** - * @inheritdoc - */ - rehash(n: number): void; - /** - * @hidden - */ - protected insert_by_val(val: T): any; - /** - * @hidden - */ - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; - /** - * @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.UniqueSet): void; - /** - * @hidden - */ - private swap_tree_set(obj); - } -} declare namespace std.HashMultiSet { type iterator = std.SetIterator; type reverse_iterator = std.SetReverseIterator; @@ -6357,8 +6084,8 @@ declare namespace std { *

    Elements with equivalent values are grouped together in the same bucket and in such a way that an * iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -6384,6 +6111,9 @@ declare namespace std { * @author Jeongho Nam */ class HashMultiSet extends base.MultiSet { + /** + * @hidden + */ private hash_buckets_; /** * @hidden @@ -6495,6 +6225,291 @@ declare namespace std { private swap_tree_set(obj); } } +declare namespace std.base { + /** + *

    An abstract set.

    + * + *

    {@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of + * individual elements based on their value.

    + * + *

    In an {@link SetContainer}, the value of an element is at the same time its key, used to uniquely + * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be modified + * once in the container - they can be inserted and removed, though.

    + * + *

    {@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    + * + *

    + *

    + * + *

    Container properties

    + *
    + *
    Associative
    + *
    + * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
    + * + *
    Set
    + *
    The value of an element is also the key used to identify it.
    + * + *
    Unique keys
    + *
    No two elements in the container can have equivalent keys.
    + *
    + * + * @param Type of the elements. Each element in a {@link SetContainer} container is also identified + * by this value (each value is itself also the element's key). + * + * @author Jeongho Nam + */ + abstract class UniqueSet extends SetContainer { + /** + * @inheritdoc + */ + count(key: T): number; + /** + *

    Extract an element.

    + * + *

    Extracts the element pointed to by val and erases it from the {@link UniqueSet}.

    + * + * @param val Value to be extracted. + * + * @return A value. + */ + extract(val: T): T; + /** + *

    Extract an element.

    + * + *

    Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

    + * + * @param it An iterator pointing an element to extract. + * + * @return An iterator pointing to the element immediately following it prior to the element being + * erased. If no such element exists,returns {@link end end()}. + */ + extract(it: SetIterator): SetIterator; + /** + *

    Extract an element.

    + * + *

    Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

    + * + * @param it An iterator pointing an element to extract. + * + * @return An iterator pointing to the element immediately following it prior to the element being + * erased. If no such element exists,returns {@link end end()}. + */ + extract(it: SetReverseIterator): SetReverseIterator; + /** + * @hidden + */ + private extract_by_key(val); + /** + * @hidden + */ + private extract_by_iterator(it); + /** + * @hidden + */ + private extract_by_reverse_iterator(it); + /** + *

    Insert an element.

    + * + *

    Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of element inserted (zero or one).

    + * + *

    Because elements in a {@link UniqueSet UniqueSets} are unique, the insertion operation checks whether + * each inserted element is equivalent to an element already in the container, and if so, the element is not + * inserted, returning an iterator to this existing element (if the function returns a value).

    + * + *

    For a similar container allowing for duplicate elements, see {@link MultiSet}.

    + * + * @param key Value to be inserted as an element. + * + * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly + * inserted element or to the equivalent element already in the {@link UniqueSet}. The + * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or + * false if an equivalent element already existed. + */ + insert(val: T): Pair, boolean>; + /** + * @inheritdoc + */ + insert(hint: SetIterator, val: T): SetIterator; + /** + * @inheritdoc + */ + insert(hint: SetReverseIterator, val: T): SetReverseIterator; + /** + * @inheritdoc + */ + insert>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + swap(obj: UniqueSet): void; + } +} +declare namespace std.HashSet { + type iterator = std.SetIterator; + type reverse_iterator = std.SetReverseIterator; +} +declare namespace std { + /** + *

    Hashed, unordered set.

    + * + *

    {@link HashSet}s are containers that store unique elements in no particular order, and which + * allow for fast retrieval of individual elements based on their value.

    + * + *

    In an {@link HashSet}, the value of an element is at the same time its key, that + * identifies it uniquely. Keys are immutable, therefore, the elements in an {@link HashSet} cannot be + * modified once in the container - they can be inserted and removed, though.

    + * + *

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

    + * + *

    {@link HashSet} containers are faster than {@link TreeSet} containers to access individual + * elements by their key, although they are generally less efficient for range iteration through a + * subset of their elements.

    + * + *

    + *

    + * + *

    Container properties

    + *
    + *
    Associative
    + *
    Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
    + * + *
    Hashed
    + *
    Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
    + * + *
    Set
    + *
    The value of an element is also the key used to identify it.
    + * + *
    Unique keys
    + *
    No two elements in the container can have equivalent keys.
    + *
    + * + * @param Type of the elements. + * Each element in an {@link HashSet} is also uniquely identified by this value. + * + * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set + * @author Jeongho Nam + */ + class HashSet extends base.UniqueSet { + /** + * @hidden + */ + private hash_buckets_; + /** + * @hidden + */ + protected init(): void; + /** + * @hidden + */ + protected construct_from_array(items: Array): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: T): SetIterator; + /** + * @inheritdoc + */ + begin(): SetIterator; + /** + * @inheritdoc + */ + begin(index: number): SetIterator; + /** + * @inheritdoc + */ + end(): SetIterator; + /** + * @inheritdoc + */ + end(index: number): SetIterator; + /** + * @inheritdoc + */ + rbegin(): SetReverseIterator; + /** + * @inheritdoc + */ + rbegin(index: number): SetReverseIterator; + /** + * @inheritdoc + */ + rend(): SetReverseIterator; + /** + * @inheritdoc + */ + rend(index: number): SetReverseIterator; + /** + * @inheritdoc + */ + bucket_count(): number; + /** + * @inheritdoc + */ + bucket_size(n: number): number; + /** + * @inheritdoc + */ + max_load_factor(): number; + /** + * @inheritdoc + */ + max_load_factor(z: number): void; + /** + * @inheritdoc + */ + bucket(key: T): number; + /** + * @inheritdoc + */ + reserve(n: number): void; + /** + * @inheritdoc + */ + rehash(n: number): void; + /** + * @hidden + */ + protected insert_by_val(val: T): any; + /** + * @hidden + */ + protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @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.UniqueSet): void; + /** + * @hidden + */ + private swap_tree_set(obj); + } +} declare namespace std.List { type iterator = std.ListIterator; type reverse_iterator = std.ListReverseIterator; @@ -6523,8 +6538,8 @@ declare namespace std { * distance between these. They also consume some extra memory to keep the linking information associated to each * element (which may be an important factor for large lists of small-sized elements).

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -6546,15 +6561,15 @@ declare namespace std { */ class List extends base.Container implements base.IDequeContainer { /** - * An iterator of beginning. + * @hidden */ protected begin_: ListIterator; /** - * An iterator of end. + * @hidden */ protected end_: ListIterator; /** - * Number of elements in the {@link List}. + * @hidden */ protected size_: number; /** @@ -7096,8 +7111,8 @@ declare namespace std { /** *

    An iterator, node of a List.

    * - *

    - * + *

    + * *

    * * @author Jeongho Nam @@ -7143,6 +7158,11 @@ declare namespace std { /** * @inheritdoc */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ value: T; /** * @inheritdoc @@ -7158,8 +7178,8 @@ declare namespace std { /** *

    A reverse-iterator of List.

    * - *

    - * + *

    + * *

    * * @param Type of the elements. @@ -7167,13 +7187,20 @@ declare namespace std { * @author Jeongho Nam */ class ListReverseIterator extends ReverseIterator, ListReverseIterator> { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: ListIterator); /** - * @inheritdoc + * @hidden */ protected create_neighbor(): ListReverseIterator; /** - * @inheritdoc + * Set value of the iterator is pointing to. + * + * @param val Value to set. */ value: T; } @@ -7208,8 +7235,8 @@ declare namespace std { * By default, if no container class is specified for a particular {@link Queue} class instantiation, the standard * container {@link List} is used.

    * - *

    - * + *

    + * *

    * * @param Type of elements. @@ -7540,8 +7567,8 @@ declare namespace std { * By default, if no container class is specified for a particular {@link Stack} class instantiation, the standard * container {@link List} is used.

    * - *

    - * + *

    + * *

    * * @param Type of elements. @@ -7651,18 +7678,18 @@ declare namespace std.base { * so that they can be interpreted when needed as more abstract (and portable) * {@link ErrorCondition error conditions}.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ abstract class ErrorInstance { /** - * A reference to an {@link ErrorCategory} object. + * @hidden */ protected category_: ErrorCategory; /** - * A numerical value identifying an error instance. + * @hidden */ protected value_: number; /** @@ -7761,15 +7788,15 @@ declare namespace std { *

    The class inherits from {@link RuntimeError}, to which it adds an {@link ErrorCode} as * member code (and defines a specialized what member).

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/system_error/system_error * @author Jeongho Nam */ class SystemError extends RuntimeError { /** - * Error code. + * @hidden */ protected code_: ErrorCode; /** @@ -7827,8 +7854,8 @@ declare namespace std { * passed by reference. As such, only one object of each of these types shall exist, each uniquely identifying its own * category: all error codes and conditions of a same category shall return a reference to same object.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/system_error/error_category * @author Jeongho Nam @@ -7955,8 +7982,8 @@ declare namespace std { *

    The {@link ErrorCategory categories} associated with the {@link ErrorCondition} and the * {@link ErrorCode} define the equivalences between them.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/system_error/error_condition * @author Jeongho Nam @@ -7988,8 +8015,8 @@ declare namespace std { *

    Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, so that they * can be interpreted when needed as more abstract (and portable) {@link ErrorCondition error conditions}.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/system_error/error_code * @author Jeongho Nam @@ -8034,8 +8061,8 @@ declare namespace std { * *

    {@link TreeMap}s are typically implemented as binary search trees.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -8063,7 +8090,7 @@ declare namespace std { */ class TreeMap extends base.UniqueMap implements base.ITreeMap { /** - * RB-Tree+ object for implemeting the {@link TreeMap}. + * @hidden */ private tree_; /** @@ -8216,8 +8243,8 @@ declare namespace std { * *

    {@link TreeMultiMap TreeMultiMaps} are typically implemented as binary search trees.

    * - *

    < - * img src="http://samchon.github.io/typescript-stl/api/assets/images/design/map_containers.png" style="max-width: 100%" />

    + *

    < + * img src="http://samchon.github.io/typescript-stl/images/design/class_diagram/map_containers.png" style="max-width: 100%" />

    * *

    Container properties

    *
    @@ -8250,6 +8277,9 @@ declare namespace std { * @author Jeongho Nam */ class TreeMultiMap extends base.MultiMap implements base.ITreeMap { + /** + * @hidden + */ private tree_; /** * Default Constructor. @@ -8377,169 +8407,6 @@ declare namespace std { private swap_tree_multimap(obj); } } -declare namespace std.TreeSet { - type iterator = std.SetIterator; - type reverse_iterator = std.SetReverseIterator; -} -declare namespace std { - /** - *

    Tree-structured set, std::set of STL.

    - * - *

    {@link TreeSet}s are containers that store unique elements following a specific order.

    - * - *

    In a {@link TreeSet}, the value of an element also identifies it (the value is itself the - * key, of type T), and each value must be unique. The value of the elements in a - * {@link TreeSet} cannot be modified once in the container (the elements are always const), but they - * can be inserted or removed from the

    - * - *

    Internally, the elements in a {@link TreeSet} are always sorted following a specific strict weak - * ordering criterion indicated by its internal comparison method (of {@link less}).

    - * - *

    {@link TreeSet} containers are generally slower than {@link HashSet} containers to access - * individual elements by their key, but they allow the direct iteration on subsets based on their - * order.

    - * - *

    {@link TreeSet}s are typically implemented as binary search trees.

    - * - *

    - *

    - * - *

    Container properties

    - *
    - *
    Associative
    - *
    - * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
    - * - *
    Ordered
    - *
    - * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
    - * - *
    Set
    - *
    The value of an element is also the key used to identify it.
    - * - *
    Unique keys
    - *
    No two elements in the container can have equivalent keys.
    - *
    - * - * @param Type of the elements. - * Each element in an {@link TreeSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/set/set - * @author Jeongho Nam - */ - class TreeSet extends base.UniqueSet implements base.ITreeSet { - /** - * RB-Tree+ object for implemeting the {@link TreeSet}. - */ - private tree_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from compare. - * - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (x: T, y: 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: (x: T, y: 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: (x: T, y: 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: (x: T, y: T) => boolean); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(val: T): SetIterator; - /** - * @inheritdoc - */ - key_comp(): (x: T, y: T) => boolean; - /** - * @inheritdoc - */ - value_comp(): (x: T, y: T) => boolean; - /** - * @inheritdoc - */ - lower_bound(val: T): SetIterator; - /** - * @inheritdoc - */ - upper_bound(val: T): SetIterator; - /** - * @inheritdoc - */ - equal_range(val: T): Pair, SetIterator>; - /** - * @hidden - */ - 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; - /** - * @inheritdoc - */ - protected handle_insert(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - protected handle_erase(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - swap(obj: base.UniqueSet): void; - /** - * @hidden - */ - private swap_tree_set(obj); - } -} declare namespace std.TreeMultiSet { type iterator = std.SetIterator; type reverse_iterator = std.SetReverseIterator; @@ -8565,8 +8432,8 @@ declare namespace std { * *

    {@link TreeMultiSet TreeMultiSets} are typically implemented as binary search trees.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -8597,7 +8464,7 @@ declare namespace std { */ class TreeMultiSet extends base.MultiSet implements base.ITreeSet { /** - * RB-Tree+ object for implemeting the {@link TreeMultiSet}. + * @hidden */ private tree_; /** @@ -8711,6 +8578,169 @@ declare namespace std { private swap_tree_set(obj); } } +declare namespace std.TreeSet { + type iterator = std.SetIterator; + type reverse_iterator = std.SetReverseIterator; +} +declare namespace std { + /** + *

    Tree-structured set, std::set of STL.

    + * + *

    {@link TreeSet}s are containers that store unique elements following a specific order.

    + * + *

    In a {@link TreeSet}, the value of an element also identifies it (the value is itself the + * key, of type T), and each value must be unique. The value of the elements in a + * {@link TreeSet} cannot be modified once in the container (the elements are always const), but they + * can be inserted or removed from the

    + * + *

    Internally, the elements in a {@link TreeSet} are always sorted following a specific strict weak + * ordering criterion indicated by its internal comparison method (of {@link less}).

    + * + *

    {@link TreeSet} containers are generally slower than {@link HashSet} containers to access + * individual elements by their key, but they allow the direct iteration on subsets based on their + * order.

    + * + *

    {@link TreeSet}s are typically implemented as binary search trees.

    + * + *

    + *

    + * + *

    Container properties

    + *
    + *
    Associative
    + *
    + * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
    + * + *
    Ordered
    + *
    + * The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order. + *
    + * + *
    Set
    + *
    The value of an element is also the key used to identify it.
    + * + *
    Unique keys
    + *
    No two elements in the container can have equivalent keys.
    + *
    + * + * @param Type of the elements. + * Each element in an {@link TreeSet} is also uniquely identified by this value. + * + * @reference http://www.cplusplus.com/reference/set/set + * @author Jeongho Nam + */ + class TreeSet extends base.UniqueSet implements base.ITreeSet { + /** + * @hidden + */ + private tree_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (x: T, y: 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: (x: T, y: 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: (x: T, y: 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: (x: T, y: T) => boolean); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(val: T): SetIterator; + /** + * @inheritdoc + */ + key_comp(): (x: T, y: T) => boolean; + /** + * @inheritdoc + */ + value_comp(): (x: T, y: T) => boolean; + /** + * @inheritdoc + */ + lower_bound(val: T): SetIterator; + /** + * @inheritdoc + */ + upper_bound(val: T): SetIterator; + /** + * @inheritdoc + */ + equal_range(val: T): Pair, SetIterator>; + /** + * @hidden + */ + 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; + /** + * @inheritdoc + */ + protected handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @inheritdoc + */ + protected handle_erase(first: SetIterator, last: SetIterator): void; + /** + * @inheritdoc + */ + swap(obj: base.UniqueSet): void; + /** + * @hidden + */ + private swap_tree_set(obj); + } +} declare namespace std { /** *

    Running on Node.

    @@ -8818,8 +8848,8 @@ declare namespace std { * end, they perform worse than the others, and have less consistent iterators and references than {@link List}s. *

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -9200,8 +9230,8 @@ declare namespace std { /** *

    An iterator of Vector.

    * - *

    - * + *

    + * *

    * * @param Type of the elements. @@ -9232,7 +9262,9 @@ declare namespace std { * @inheritdoc */ /** - * Set value. + * Set value of the iterator is pointing to. + * + * @param val Value to set. */ value: T; /** @@ -9277,8 +9309,8 @@ declare namespace std { /** *

    A reverse-iterator of Vector.

    * - *

    - * + *

    + * *

    * * @param Type of the elements. @@ -9286,13 +9318,20 @@ declare namespace std { * @author Jeongho Nam */ class VectorReverseIterator extends ReverseIterator, VectorReverseIterator> implements base.IArrayIterator { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: VectorIterator); /** - * @inheritdoc + * @hidden */ protected create_neighbor(): VectorReverseIterator; /** - * Set value. + * Set value of the iterator is pointing to. + * + * @param val Value to set. */ value: T; /** @@ -9353,7 +9392,13 @@ declare namespace std.base { * @author Jeongho Nam */ class HashBuckets { + /** + * @hidden + */ private buckets_; + /** + * @hidden + */ private item_size_; /** * Default Constructor. @@ -9400,8 +9445,8 @@ declare namespace std.base { *

    Elements with equivalent keys are grouped together in the same bucket and in such a way that * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -9696,8 +9741,8 @@ declare namespace std.base { /** *

    Hash buckets storing {@link MapIterator MapIterators}.

    * - *

    - * + *

    + * *

    * * @author Jeongho Nam @@ -9727,8 +9772,8 @@ declare namespace std.base { * elements by their key, although they are generally less efficient for range iteration through a * subset of their elements.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -9951,8 +9996,8 @@ declare namespace std.base { /** *

    Hash buckets storing {@link SetIterator SetIterators}.

    * - *

    - * + *

    + * *

    * * @author Jeongho Nam @@ -9993,8 +10038,8 @@ declare namespace std.base { * beginning or the end, {@link IArray} objects perform worse and have less consistent iterators and references * than {@link List Lists}

    . * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -10107,8 +10152,8 @@ declare namespace std.base { *

    There is not a single type of {@link IArrayIterator random-access iterator}: Each container may define its * own specific iterator type able to iterate through it and access its elements.

    * - *

    - * + *

    + * *

    * * @reference http://www.cplusplus.com/reference/iterator/RandomAccessIterator @@ -10138,8 +10183,8 @@ declare namespace std.base { *

    {@link IContainer} is an interface designed for sequence containers. Sequence containers of STL * (Standard Template Library) are based on the {@link IContainer}.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -10330,8 +10375,8 @@ declare namespace std.base { /** *

    An interface for deque

    * - *

    - * + *

    + * *

    * * @author Jeongho Nam @@ -10360,8 +10405,8 @@ declare namespace std.base { /** *

    An interface for linear containers.

    * - *

    - * + *

    + * *

    * * @author Jeonngho Nam @@ -10522,7 +10567,7 @@ declare namespace std.base { * * * - *

    * *

    These constraints enforce a critical property of red-black trees: the path from the root to the farthest @@ -10717,7 +10762,7 @@ declare namespace std.base { * the only loop, and any rotations occur after this loop, this proves that a constant number of rotations * occur.

    * - *

    * * @param N A node to be inserted or swapped. @@ -10751,7 +10796,7 @@ declare namespace std.base { * node are black) is still violated, but now we can resolve this by * continuing to case 5.

    * - *

    * * @param N A node to be inserted or swapped. @@ -10782,7 +10827,7 @@ declare namespace std.base { * through {@link XTreeNode.parent P}. In each case, this is the only * black node of the three.

    * - *

    * * @param N A node to be inserted or swapped. @@ -10936,7 +10981,7 @@ declare namespace std.base { /** *

    {@link XTreeNode.sibling S} is red.

    * - *

    * *

    In this case we reverse the colors of {@link XTreeNode.parent P} and @@ -10958,7 +11003,7 @@ declare namespace std.base { *

    {@link XTreeNode.parent P}, {@link XTreeNode.sibling S}, and {@link XTreeNode.sibling * S}'s children are black.

    * - *

    * *

    In this case, we simply repaint {@link XTreeNode.sibling S} red. The @@ -10982,7 +11027,7 @@ declare namespace std.base { *

    {@link XTreeNode.sibling S} and {@link XTreeNode.sibling S}'s children are * black, but {@link XTreeNode.parent P} is red.

    * - *

    * *

    In this case, we simply exchange the colors of {@link XTreeNode.sibling S} and @@ -10999,7 +11044,7 @@ declare namespace std.base { * left child is red, {@link XTreeNode.sibling S}'s right child is * black, and N is the left child of its parent.

    * - *

    * *

    In this case we rotate right at {@link XTreeNode.sibling S}, so that @@ -11038,7 +11083,7 @@ declare namespace std.base { *

    Thus, the paths passing through N pass through one additional * black node.

    * - *

    * *

    Meanwhile, if a path does not go through N, then there are two possibilities:

    @@ -11122,8 +11167,8 @@ declare namespace std.base { * *

    {@link ITreeMap TreeMultiMaps} are typically implemented as binary search trees.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -11257,13 +11302,19 @@ declare namespace std.base { /** *

    A red-black tree storing {@link MapIterator MapIterators}.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ class PairTree extends XTree> { + /** + * @hidden + */ private map_; + /** + * @hidden + */ private compare_; /** * Default Constructor. @@ -11409,8 +11460,8 @@ declare namespace std.base { * *

    {@link ITreeSet TreeMultiSets} are typically implemented as binary search trees.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -11551,13 +11602,19 @@ declare namespace std.base { /** *

    A red-black Tree storing {@link SetIterator SetIterators}.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ class AtomicTree extends XTree> { + /** + * @hidden + */ private set_; + /** + * @hidden + */ private compare_; /** * Default Constructor. @@ -11738,27 +11795,3 @@ declare namespace std.base { uncle: XTreeNode; } } -declare namespace std.example { - function test_all(): void; -} -declare namespace std.example { - function test_bind(): void; -} -declare namespace std.example { - function test_deque(): void; -} -declare namespace std.example { - function test_for_each(): void; -} -declare namespace std.example { - function test_hash_map(): void; -} -declare namespace std.example { - function test_list(): void; -} -declare namespace std.example { - function sorting(): void; -} -declare namespace std.example { - function tree_set(): void; -} From 98522eee4825682cc8fa73da4a9a8ba5f34aaf18 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Fri, 12 Aug 2016 09:51:01 +0900 Subject: [PATCH 031/844] TypeScript-STL & Samchon Framework --- typescript-stl/typescript-stl.d.ts | 120 ++++++++++++++--------------- 1 file changed, 60 insertions(+), 60 deletions(-) diff --git a/typescript-stl/typescript-stl.d.ts b/typescript-stl/typescript-stl.d.ts index 9e491ff258..5a83a405cd 100644 --- a/typescript-stl/typescript-stl.d.ts +++ b/typescript-stl/typescript-stl.d.ts @@ -2744,8 +2744,8 @@ declare namespace std.base { /** *

    An abstract container.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -2865,8 +2865,8 @@ declare namespace std { *

    There is not a single type of {@link Iterator bidirectional iterator}: {@link IContainer Each container} * may define its own specific iterator type able to iterate through it and access its elements.

    * - *

    - * + *

    + * *

    * * @reference http://www.cplusplus.com/reference/iterator/BidirectionalIterator @@ -2951,8 +2951,8 @@ declare namespace std { * first element in a range is reversed, the reversed iterator points to the element before the first element (this * would be the past-the-end element of the reversed range).

    * - *

    - * + *

    + * *

    * * @reference http://www.cplusplus.com/reference/iterator/reverse_iterator @@ -3622,8 +3622,8 @@ declare namespace std { *

    All objects thrown by components of the standard library are derived from this class. * Therefore, all standard exceptions can be caught by catching this type by reference.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/exception/exception * @author Jeongho Nam @@ -3671,8 +3671,8 @@ declare namespace std { * *

    It is used as a base class for several logical error exceptions.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/logic_error * @author Jeongho Nam @@ -3697,8 +3697,8 @@ declare namespace std { *

    No component of the standard library throws exceptions of this type. It is designed as a standard * exception to be thrown by programs.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/domain_error * @author Jeongho Nam @@ -3719,8 +3719,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal invalid arguments.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/invalid_argument * @author Jeongho Nam @@ -3741,8 +3741,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library, * such as vector and string also throw exceptions of this type to signal errors resizing.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/length_error * @author Jeongho Nam @@ -3764,8 +3764,8 @@ declare namespace std { * such as vector, deque, string and bitset also throw exceptions of this type to signal arguments * out of range.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/out_of_range * @author Jeongho Nam @@ -3786,8 +3786,8 @@ declare namespace std { * *

    It is used as a base class for several runtime error exceptions.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/runtime_error * @author Jeongho Nam @@ -3808,8 +3808,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal range errors.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/overflow_error * @author Jeongho Nam @@ -3830,8 +3830,8 @@ declare namespace std { *

    No component of the standard library throws exceptions of this type. It is designed as a standard * exception to be thrown by programs.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/underflow_error * @author Jeongho Nam @@ -3853,8 +3853,8 @@ declare namespace std { *

    It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal range errors.

    * - *

    - *

    + *

    + *

    * * @reference http://www.cplusplus.com/reference/stdexcept/range_error * @author Jeongho Nam @@ -4415,8 +4415,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -4813,8 +4813,8 @@ declare namespace std { /** *

    An iterator of {@link MapContainer map container}.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ @@ -4884,8 +4884,8 @@ declare namespace std { /** *

    A reverse-iterator of {@link MapContainer map container}.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ @@ -4932,8 +4932,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -5477,8 +5477,8 @@ declare namespace std { *

    Elements with equivalent keys are grouped together in the same bucket and in such a way that * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -5637,8 +5637,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -5914,8 +5914,8 @@ declare namespace std { /** *

    An iterator of a Set.

    * - *

    - *

    + *

    + *

    * * @author Jeongho Nam */ @@ -5973,8 +5973,8 @@ declare namespace std { /** *

    A reverse-iterator of Set.

    * - *

    - *

    + *

    + *

    * * @param Type of the elements. * @@ -6240,8 +6240,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

    * - *

    - *

    + *

    + *

    * *

    Container properties

    *
    @@ -7235,8 +7235,8 @@ declare namespace std { * By default, if no container class is specified for a particular {@link Queue} class instantiation, the standard * container {@link List} is used.

    * - *

    - * + *

    + * *

    * * @param Type of elements. @@ -7567,8 +7567,8 @@ declare namespace std { * By default, if no container class is specified for a particular {@link Stack} class instantiation, the standard * container {@link List} is used.

    * - *

    - * + *

    + * *

    * * @param Type of elements. @@ -9772,8 +9772,8 @@ declare namespace std.base { * elements by their key, although they are generally less efficient for range iteration through a * subset of their elements.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -9996,8 +9996,8 @@ declare namespace std.base { /** *

    Hash buckets storing {@link SetIterator SetIterators}.

    * - *

    - * + *

    + * *

    * * @author Jeongho Nam @@ -10152,8 +10152,8 @@ declare namespace std.base { *

    There is not a single type of {@link IArrayIterator random-access iterator}: Each container may define its * own specific iterator type able to iterate through it and access its elements.

    * - *

    - * + *

    + * *

    * * @reference http://www.cplusplus.com/reference/iterator/RandomAccessIterator @@ -10183,8 +10183,8 @@ declare namespace std.base { *

    {@link IContainer} is an interface designed for sequence containers. Sequence containers of STL * (Standard Template Library) are based on the {@link IContainer}.

    * - *

    - * + *

    + * *

    * *

    Container properties

    @@ -10375,8 +10375,8 @@ declare namespace std.base { /** *

    An interface for deque

    * - *

    - * + *

    + * *

    * * @author Jeongho Nam @@ -10405,8 +10405,8 @@ declare namespace std.base { /** *

    An interface for linear containers.

    * - *

    - * + *

    + * *

    * * @author Jeonngho Nam From d44c56c717ef10b3d9aecb3b59df6dc6e03369a9 Mon Sep 17 00:00:00 2001 From: Michael Zlatkovsky Date: Fri, 12 Aug 2016 18:32:57 -0700 Subject: [PATCH 032/844] Update common runtime and add Excel 1.3 Also strip out filenames that start with _ in Word APIs --- office-js/office-js.d.ts | 1460 ++++++++++++++++++++++++-------------- 1 file changed, 941 insertions(+), 519 deletions(-) diff --git a/office-js/office-js.d.ts b/office-js/office-js.d.ts index f2bebfe3da..4f21022fe5 100644 --- a/office-js/office-js.d.ts +++ b/office-js/office-js.d.ts @@ -53,7 +53,7 @@ declare namespace Office { displayLanguage: string; license: string; touchEnabled: boolean; - ui: UI; + ui: UI; requirements: { /** * Check if the specified requirement set is supported by the host Office application. @@ -67,51 +67,54 @@ declare namespace Office { message: string; name: string; } - export interface UI { - /** - * Displays a dialog to show or collect information from the user or to facilitate Web navigation. - * @param startAddress Accepts the initial HTTPS Url that opens in the dialog. - * @param options Optional. Accepts a DialogOptions object to define dialog behaviors. - * @param callback Optional. Accepts a callback method to handle the dialog creation attempt. - */ - displayDialogAsync(startAddress: string, options?: DialogOptions, callback?: (result: AsyncResult) => void): void; - /** - * When called from an active add-in dialog, asynchronously closes the dialog. - */ - close(): void; - /** - * Synchronously delivers a message from the dialog to its parent add-in. - * @param messageObject Accepts a message from the dialog to deliver to the add-in. - */ - messageParent(messageObject: any): void; + export interface UI { + /** + * Displays a dialog to show or collect information from the user or to facilitate Web navigation. + * @param startAddress Accepts the initial HTTPS Url that opens in the dialog. + * @param options Optional. Accepts a DialogOptions object to define dialog behaviors. + * @param callback Optional. Accepts a callback method to handle the dialog creation attempt. + */ + displayDialogAsync(startAddress: string, options?: DialogOptions, callback?: (result: AsyncResult) => void): void; + /** + * When called from an active add-in dialog, asynchronously closes the dialog. + */ + close(): void; + /** + * Synchronously delivers a message from the dialog to its parent add-in. + * @param messageObject Accepts a message from the dialog to deliver to the add-in. + */ + messageParent(messageObject: any): void; } export interface DialogOptions { /** * Optional. Defines the width of the dialog as a percentage of the current display. Defaults to 99%. 250px minimum. */ - height?: number, + height?: number, /** * Optional. Defines the height of the dialog as a percentage of the current display. Defaults to 99%. 150px minimum. */ - width?: number, + width?: number, /** * Optional. Specifies whether the dialog can only display pages that have HTTPS URLs. */ - requireHTTPS?: boolean, + requireHTTPS?: boolean, /** * Optional. Determines whether the dialog is safe to display within a Web frame. */ xFrameDenySafe?: boolean, } } -declare namespace OfficeExtension { + +declare module OfficeExtension { /** An abstract proxy object that represents an object in an Office document. You create proxy objects from the context (or from other proxy objects), add commands to a queue to act on the object, and then synchronize the proxy object state with the document by calling "context.sync()". */ class ClientObject { /** The request context associated with the object */ context: ClientRequestContext; + /** Returns a boolean value for whether the corresponding object is null. You must call "context.sync()" before reading the isNull property. [Api set: ExcelApi 1.3 (Preview), WordApi 1.3] */ + isNull: boolean; } } -declare namespace OfficeExtension { +declare module OfficeExtension { interface LoadOption { select?: string | string[]; expand?: string | string[]; @@ -127,18 +130,18 @@ declare namespace OfficeExtension { load(object: ClientObject, option?: string | string[] | LoadOption): void; /** Adds a trace message to the queue. If the promise returned by "context.sync()" is rejected due to an error, this adds a ".traceMessages" array to the OfficeExtension.Error object, containing all trace messages that were executed. These messages can help you monitor the program execution sequence and detect the cause of the error. */ trace(message: string): void; - /** Synchronizes the state between JavaScript proxy objects and the Office document, by executing instructions queued on the request context and retrieving properties of loaded Office objects for use in your code.�This method returns a promise, which is resolved when the synchronization is complete. */ + /** Synchronizes the state between JavaScript proxy objects and the Office document, by executing instructions queued on the request context and retrieving properties of loaded Office objects for use in your code. This method returns a promise, which is resolved when the synchronization is complete. */ sync(passThroughValue?: T): IPromise; } } -declare namespace OfficeExtension { +declare module OfficeExtension { /** Contains the result for methods that return primitive types. The object's value property is retrieved from the document after "context.sync()" is invoked. */ class ClientResult { /** The value of the result that is retrieved from the document after "context.sync()" is invoked. */ value: T; } } -declare namespace OfficeExtension { +declare module OfficeExtension { /** The error object returned by "context.sync()", if a promise is rejected due to an error while processing the request. */ class Error { /** Error name: "OfficeExtension.Error".*/ @@ -158,68 +161,186 @@ declare namespace OfficeExtension { }; } } -declare namespace OfficeExtension { +declare module OfficeExtension { class ErrorCodes { static accessDenied: string; static generalException: string; static activityLimitReached: string; + static invalidObjectPath: string; + static propertyNotLoaded: string; + static valueNotLoaded: string; + static invalidRequestContext: string; + static invalidArgument: string; + static runMustReturnPromise: string; + static cannotRegisterEvent: string; } } -declare namespace OfficeExtension { - /** A Promise object that represents a deferred interaction with the host Office application. Promises can be chained via ".then", and errors can be caught via ".catch". Remember to always use a ".catch" on the outer promise, and to return intermediary promises so as not to break the promise chain. */ +declare module OfficeExtension { + /** An IPromise object that represents a deferred interaction with the host Office application. */ interface IPromise { /** * This method will be called once the previous promise has been resolved. * Both the onFulfilled on onRejected callbacks are optional. * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. */ then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => IPromise): IPromise; + /** * This method will be called once the previous promise has been resolved. * Both the onFulfilled on onRejected callbacks are optional. * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. */ then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => U): IPromise; + /** * This method will be called once the previous promise has been resolved. * Both the onFulfilled on onRejected callbacks are optional. * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. */ then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => void): IPromise; + /** * This method will be called once the previous promise has been resolved. * Both the onFulfilled on onRejected callbacks are optional. * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. */ then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => IPromise): IPromise; + /** * This method will be called once the previous promise has been resolved. * Both the onFulfilled on onRejected callbacks are optional. * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. */ then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): IPromise; + /** * This method will be called once the previous promise has been resolved. * Both the onFulfilled on onRejected callbacks are optional. * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. */ then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => void): IPromise; + + /** * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. * @param onRejected function to be called if or when the promise rejects. */ catch(onRejected?: (error: any) => IPromise): IPromise; + /** * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. * @param onRejected function to be called if or when the promise rejects. */ catch(onRejected?: (error: any) => U): IPromise; + + /** + * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. + * @param onRejected function to be called if or when the promise rejects. + */ + catch(onRejected?: (error: any) => void): IPromise; + } + + /** An Promise object that represents a deferred interaction with the host Office application. The publically-consumable OfficeExtension.Promise is available starting in ExcelApi 1.2 and WordApi 1.2. Promises can be chained via ".then", and errors can be caught via ".catch". Remember to always use a ".catch" on the outer promise, and to return intermediary promises so as not to break the promise chain. When a "native" Promise implementation is available, OfficeExtension.Promise will switch to use the native Promise instead. */ + export class Promise implements IPromise + { + /** + * Creates a new promise based on a function that accepts resolve and reject handlers. + */ + constructor(func: (resolve, reject) => void); + + /** + * Creates a promise that resolves when all of the child promises resolve. + */ + static all(promises: OfficeExtension.IPromise[]): IPromise; + + /** + * Creates a promise that is resolved. + */ + static resolve(value: U): IPromise; + + /** + * Creates a promise that is rejected. + */ + static reject(error: any): IPromise; + + /* This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => IPromise): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => U): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => void): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => IPromise): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => void): IPromise; + + + /** + * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. + * @param onRejected function to be called if or when the promise rejects. + */ + catch(onRejected?: (error: any) => IPromise): IPromise; + + /** + * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. + * @param onRejected function to be called if or when the promise rejects. + */ + catch(onRejected?: (error: any) => U): IPromise; + /** * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. * @param onRejected function to be called if or when the promise rejects. @@ -227,7 +348,8 @@ declare namespace OfficeExtension { catch(onRejected?: (error: any) => void): IPromise; } } -declare namespace OfficeExtension { + +declare module OfficeExtension { /** Collection of tracked objects, contained within a request context. See "context.trackedObjects" for more information. */ class TrackedObjects { /** Track a new object for automatic adjustment based on surrounding changes in the document. Only some object types require this. If you are using an object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ @@ -241,6 +363,26 @@ declare namespace OfficeExtension { } } +declare module OfficeExtension { + export class EventHandlers { + constructor(context: ClientRequestContext, parentObject: ClientObject, name: string, eventInfo: EventInfo); + add(handler: (args: T) => IPromise): EventHandlerResult; + remove(handler: (args: T) => IPromise): void; + removeAll(): void; + } + + export class EventHandlerResult { + constructor(context: ClientRequestContext, handlers: EventHandlers, handler: (args: T) => IPromise); + remove(): void; + } + + export interface EventInfo { + registerFunc: (callback: (args: any) => void) => IPromise; + unregisterFunc: (callback: (args: any) => void) => IPromise; + eventArgsTransformFunc: (args: any) => IPromise; + } +} + declare namespace Office { /** * Returns a promise of an object described in the expression. Callback is invoked only if method fails. @@ -467,7 +609,7 @@ declare namespace Office { * asyncContext: Object keeping state for the callback * @param callback The optional callback method */ - setDataAsync(data: TableData|any, options?: any, callback?: (result: AsyncResult) => void): void; + setDataAsync(data: TableData | any, options?: any, callback?: (result: AsyncResult) => void): void; } export interface Bindings { document: Document; @@ -743,7 +885,7 @@ declare namespace Office { * asyncContext: Object keeping state for the callback * @param callback The optional callback method */ - goToByIdAsync(id: string|number, goToType: GoToType, options?: any, callback?: (result: AsyncResult) => void): void; + goToByIdAsync(id: string | number, goToType: GoToType, options?: any, callback?: (result: AsyncResult) => void): void; /** * Removes an event handler for the specified event type. * @param eventType The event type. For document can be 'DocumentSelectionChanged' @@ -761,7 +903,7 @@ declare namespace Office { * asyncContext: Object keeping state for the callback * @param callback The optional callback method */ - setSelectedDataAsync(data: string|TableData|any[][], options?: any, callback?: (result: AsyncResult) => void): void; + setSelectedDataAsync(data: string | TableData | any[][], options?: any, callback?: (result: AsyncResult) => void): void; } export interface File { size: number; @@ -853,7 +995,7 @@ declare namespace Office { * asyncContext: Object keeping state for the callback * @param callback The optional callback method */ - addColumnsAsync(tableData: TableData|any[][], options?: any, callback?: (result: AsyncResult) => void): void; + addColumnsAsync(tableData: TableData | any[][], options?: any, callback?: (result: AsyncResult) => void): void; /** * Adds the specified rows to the table * @param rows A 2D array with the rows to add @@ -861,7 +1003,7 @@ declare namespace Office { * asyncContext: Object keeping state for the callback * @param callback The optional callback method */ - addRowsAsync(rows: TableData|any[][], options?: any, callback?: (result: AsyncResult) => void): void; + addRowsAsync(rows: TableData | any[][], options?: any, callback?: (result: AsyncResult) => void): void; /** * Clears the table * @param options Syntax example: {asyncContext:context} @@ -1503,9 +1645,238 @@ declare namespace Office { getWSSUrlAsync(options?: any, callback?: (result: AsyncResult) => void): void; } } - - -declare namespace Excel { +declare module Excel { + interface ThreeArrowsSet { + [index: number]: Icon; + redDownArrow: Icon; + yellowSideArrow: Icon; + greenUpArrow: Icon; + } + interface ThreeArrowsGraySet { + [index: number]: Icon; + grayDownArrow: Icon; + graySideArrow: Icon; + grayUpArrow: Icon; + } + interface ThreeFlagsSet { + [index: number]: Icon; + redFlag: Icon; + yellowFlag: Icon; + greenFlag: Icon; + } + interface ThreeTrafficLights1Set { + [index: number]: Icon; + redCircleWithBorder: Icon; + yellowCircle: Icon; + greenCircle: Icon; + } + interface ThreeTrafficLights2Set { + [index: number]: Icon; + redTrafficLight: Icon; + yellowTrafficLight: Icon; + greenTrafficLight: Icon; + } + interface ThreeSignsSet { + [index: number]: Icon; + redDiamond: Icon; + yellowTriangle: Icon; + greenCircle: Icon; + } + interface ThreeSymbolsSet { + [index: number]: Icon; + redCrossSymbol: Icon; + yellowExclamationSymbol: Icon; + greenCheckSymbol: Icon; + } + interface ThreeSymbols2Set { + [index: number]: Icon; + redCross: Icon; + yellowExclamation: Icon; + greenCheck: Icon; + } + interface FourArrowsSet { + [index: number]: Icon; + redDownArrow: Icon; + yellowDownInclineArrow: Icon; + yellowUpInclineArrow: Icon; + greenUpArrow: Icon; + } + interface FourArrowsGraySet { + [index: number]: Icon; + grayDownArrow: Icon; + grayDownInclineArrow: Icon; + grayUpInclineArrow: Icon; + grayUpArrow: Icon; + } + interface FourRedToBlackSet { + [index: number]: Icon; + blackCircle: Icon; + grayCircle: Icon; + pinkCircle: Icon; + redCircle: Icon; + } + interface FourRatingSet { + [index: number]: Icon; + oneBar: Icon; + twoBars: Icon; + threeBars: Icon; + fourBars: Icon; + } + interface FourTrafficLightsSet { + [index: number]: Icon; + blackCircleWithBorder: Icon; + redCircleWithBorder: Icon; + yellowCircle: Icon; + greenCircle: Icon; + } + interface FiveArrowsSet { + [index: number]: Icon; + redDownArrow: Icon; + yellowDownInclineArrow: Icon; + yellowSideArrow: Icon; + yellowUpInclineArrow: Icon; + greenUpArrow: Icon; + } + interface FiveArrowsGraySet { + [index: number]: Icon; + grayDownArrow: Icon; + grayDownInclineArrow: Icon; + graySideArrow: Icon; + grayUpInclineArrow: Icon; + grayUpArrow: Icon; + } + interface FiveRatingSet { + [index: number]: Icon; + noBars: Icon; + oneBar: Icon; + twoBars: Icon; + threeBars: Icon; + fourBars: Icon; + } + interface FiveQuartersSet { + [index: number]: Icon; + whiteCircleAllWhiteQuarters: Icon; + circleWithThreeWhiteQuarters: Icon; + circleWithTwoWhiteQuarters: Icon; + circleWithOneWhiteQuarter: Icon; + blackCircle: Icon; + } + interface ThreeStarsSet { + [index: number]: Icon; + silverStar: Icon; + halfGoldStar: Icon; + goldStar: Icon; + } + interface ThreeTrianglesSet { + [index: number]: Icon; + redDownTriangle: Icon; + yellowDash: Icon; + greenUpTriangle: Icon; + } + interface FiveBoxesSet { + [index: number]: Icon; + noFilledBoxes: Icon; + oneFilledBox: Icon; + twoFilledBoxes: Icon; + threeFilledBoxes: Icon; + fourFilledBoxes: Icon; + } + interface IconCollections { + threeArrows: ThreeArrowsSet; + threeArrowsGray: ThreeArrowsGraySet; + threeFlags: ThreeFlagsSet; + threeTrafficLights1: ThreeTrafficLights1Set; + threeTrafficLights2: ThreeTrafficLights2Set; + threeSigns: ThreeSignsSet; + threeSymbols: ThreeSymbolsSet; + threeSymbols2: ThreeSymbols2Set; + fourArrows: FourArrowsSet; + fourArrowsGray: FourArrowsGraySet; + fourRedToBlack: FourRedToBlackSet; + fourRating: FourRatingSet; + fourTrafficLights: FourTrafficLightsSet; + fiveArrows: FiveArrowsSet; + fiveArrowsGray: FiveArrowsGraySet; + fiveRating: FiveRatingSet; + fiveQuarters: FiveQuartersSet; + threeStars: ThreeStarsSet; + threeTriangles: ThreeTrianglesSet; + fiveBoxes: FiveBoxesSet; + } + var icons: IconCollections; + /** + * + * Provides information about the binding that raised the SelectionChanged event. + * + * [Api set: ExcelApi 1.2] + */ + interface BindingSelectionChangedEventArgs { + /** + * + * Gets the Binding object that represents the binding that raised the SelectionChanged event. + * + * [Api set: ExcelApi 1.2] + */ + binding: Excel.Binding; + /** + * + * Gets the number of columns selected. + * + * [Api set: ExcelApi 1.2] + */ + columnCount: number; + /** + * + * Gets the number of rows selected. + * + * [Api set: ExcelApi 1.2] + */ + rowCount: number; + /** + * + * Gets the index of the first column of the selection (zero-based). + * + * [Api set: ExcelApi 1.2] + */ + startColumn: number; + /** + * + * Gets the index of the first row of the selection (zero-based). + * + * [Api set: ExcelApi 1.2] + */ + startRow: number; + } + /** + * + * Provides information about the binding that raised the DataChanged event. + * + * [Api set: ExcelApi 1.2] + */ + interface BindingDataChangedEventArgs { + /** + * + * Gets the Binding object that represents the binding that raised the DataChanged event. + * + * [Api set: ExcelApi 1.2] + */ + binding: Excel.Binding; + } + /** + * + * Provides information about the document that raised the SelectionChanged event. + * + * [Api set: ExcelApi 1.2] + */ + interface SelectionChangedEventArgs { + /** + * + * Gets the workbook object that raised the SelectionChanged event. + * + * [Api set: ExcelApi 1.2] + */ + workbook: Excel.Workbook; + } /** * * Represents the Excel application that manages the workbook. @@ -1546,8 +1917,10 @@ declare namespace Excel { private m_bindings; private m_functions; private m_names; + private m_pivotTables; private m_tables; private m_worksheets; + private m_selectionChanged; /** * * Represents Excel application instance that contains this workbook. Read-only. @@ -1576,6 +1949,13 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ names: Excel.NamedItemCollection; + /** + * + * Represents a collection of PivotTables associated with the workbook. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + pivotTables: Excel.PivotTableCollection; /** * * Represents a collection of tables associated with the workbook. Read-only. @@ -1601,6 +1981,13 @@ declare namespace Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.Workbook; + /** + * + * Occurs when the selection in the document is changed. + * + * [Api set: ExcelApi 1.2] + */ + onSelectionChanged: OfficeExtension.EventHandlers; } /** * @@ -1612,6 +1999,7 @@ declare namespace Excel { private m_charts; private m_id; private m_name; + private m_pivotTables; private m_position; private m_protection; private m_tables; @@ -1623,6 +2011,13 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ charts: Excel.ChartCollection; + /** + * + * Collection of PivotTables that are part of the worksheet. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + pivotTables: Excel.PivotTableCollection; /** * * Returns sheet protection object for a worksheet. @@ -1702,7 +2097,7 @@ declare namespace Excel { * * The used range is the smallest range that encompasses any cells that have a value or formatting assigned to them. If the worksheet is blank, this function will return the top left cell. * - * @param valuesOnly Considers only cells with values as used cells (ignores formatting). [Parameter available: ExcelApi 1.2] + * @param valuesOnly Considers only cells with values as used cells (ignores formatting). [Api set: ExcelApi 1.2] * * [Api set: ExcelApi 1.1] */ @@ -1747,6 +2142,15 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getItem(key: string): Excel.Worksheet; + /** + * + * Gets a worksheet object using its Name or ID. If the worksheet does not exist, the returned object's isNull property will be true. + * + * @param key The Name or ID of the worksheet. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItemOrNull(key: string): Excel.Worksheet; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -1777,7 +2181,7 @@ declare namespace Excel { protected: boolean; /** * - * Protect a worksheet. It throws if the worksheet has been protected. + * Protects a worksheet. Fails if the worksheet has been protected. * * @param options sheet protection options. * @@ -1786,7 +2190,7 @@ declare namespace Excel { protect(options?: Excel.WorksheetProtectionOptions): void; /** * - * Unprotect a worksheet + * Unprotects a worksheet. * * [Api set: ExcelApi 1.2] */ @@ -1868,7 +2272,7 @@ declare namespace Excel { allowInsertRows?: boolean; /** * - * Represents the worksheet protection option of allowing using pivot table feature. + * Represents the worksheet protection option of allowing using PivotTable feature. * * [Api set: ExcelApi 1.2] */ @@ -1909,6 +2313,8 @@ declare namespace Excel { private m_values; private m_worksheet; private m__ReferenceId; + private _ensureInteger(num, methodName); + private _getAdjacentRange(functionName, count, referenceRange, rowDirection, columnDirection); /** * * Returns a format object, encapsulating the range's font, fill, borders, alignment, and other properties. Read-only. @@ -1916,6 +2322,12 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ format: Excel.RangeFormat; + /** + * + * Represents the range sort of the current range. + * + * [Api set: ExcelApi 1.2] + */ sort: Excel.RangeSort; /** * @@ -2089,6 +2501,24 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getColumn(column: number): Excel.Range; + /** + * + * Gets a certain number of columns to the right of the current Range object. + * + * @param count The number of columns to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. + * + * [Api set: ExcelApi 1.2] + */ + getColumnsAfter(count?: number): Excel.Range; + /** + * + * Gets a certain number of columns to the left of the current Range object. + * + * @param count The number of columns to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. + * + * [Api set: ExcelApi 1.2] + */ + getColumnsBefore(count?: number): Excel.Range; /** * * Gets an object that represents the entire column of the range. @@ -2112,6 +2542,15 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getIntersection(anotherRange: Excel.Range | string): Excel.Range; + /** + * + * Gets the range object that represents the rectangular intersection of the given ranges. If no intersection is found, will return a null object. + * + * @param anotherRange The range object or range address that will be used to determine the intersection of ranges. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getIntersectionOrNull(anotherRange: Excel.Range | string): Excel.Range; /** * * Gets the last cell within the range. For example, the last cell of "B2:D5" is "D5". @@ -2143,6 +2582,16 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getOffsetRange(rowOffset: number, columnOffset: number): Excel.Range; + /** + * + * Gets a Range object similar to the current Range object, but with its bottom-right corner expanded (or contracted) by some number of rows and columns. + * + * @param deltaRows The number of rows by which to expand the bottom-right corner, relative to the current range. Use a positive number to expand the range, or a negative number to decrease it. + * @param deltaColumns The number of columnsby which to expand the bottom-right corner, relative to the current range. Use a positive number to expand the range, or a negative number to decrease it. + * + * [Api set: ExcelApi 1.2] + */ + getResizedRange(deltaRows: number, deltaColumns: number): Excel.Range; /** * * Gets a row contained in the range. @@ -2152,15 +2601,40 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getRow(row: number): Excel.Range; + /** + * + * Gets a certain number of rows above the current Range object. + * + * @param count The number of rows to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. + * + * [Api set: ExcelApi 1.2] + */ + getRowsAbove(count?: number): Excel.Range; + /** + * + * Gets a certain number of rows below the current Range object. + * + * @param count The number of rows to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1. + * + * [Api set: ExcelApi 1.2] + */ + getRowsBelow(count?: number): Excel.Range; /** * * Returns the used range of the given range object. * - * @param valuesOnly Considers only cells with values as used cells. [Parameter available: ExcelApi 1.2] + * @param valuesOnly Considers only cells with values as used cells. [Api set: ExcelApi 1.2] * * [Api set: ExcelApi 1.1] */ getUsedRange(valuesOnly?: boolean): Excel.Range; + /** + * + * Represents the visible rows of the current range. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getVisibleView(): Excel.RangeView; /** * * Inserts a cell or a range of cells into the worksheet in place of this range, and shifts the other cells to make space. Returns a new Range object at the now blank space. @@ -2207,6 +2681,129 @@ declare namespace Excel { interface RangeReference { address: string; } + /** + * + * RangeView represents a set of visible cells of the parent range. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + class RangeView extends OfficeExtension.ClientObject { + private m_columnCount; + private m_formulas; + private m_formulasLocal; + private m_formulasR1C1; + private m_numberFormat; + private m_rowCount; + private m_rows; + private m_text; + private m_valueTypes; + private m_values; + /** + * + * Represents a collection of range views associated with the range. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + rows: Excel.RangeViewCollection; + /** + * + * Returns the number of visible columns. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + columnCount: number; + /** + * + * Represents the formula in A1-style notation. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + formulas: Array>; + /** + * + * Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become "=SUMME(A1; 1,5)" in German. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + formulasLocal: Array>; + /** + * + * Represents the formula in R1C1-style notation. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + formulasR1C1: Array>; + /** + * + * Represents Excel's number format code for the given cell. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + numberFormat: Array>; + /** + * + * Returns the number of visible rows. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + rowCount: number; + /** + * + * Text values of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + text: Array>; + /** + * + * Represents the type of data of each cell. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + valueTypes: Array>; + /** + * + * Represents the raw values of the specified range view. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + values: Array>; + /** + * + * Gets the parent range associated with the current RangeView. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getRange(): Excel.Range; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.RangeView; + } + /** + * + * Represents a collection of worksheet objects that are part of the workbook. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + class RangeViewCollection extends OfficeExtension.ClientObject { + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Gets a RangeView Row via it's index. Zero-Indexed. + * + * @param index Index of the visible row. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItem(index: number): Excel.RangeView; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.RangeViewCollection; + } /** * * A collection of all the nameditem objects that are part of the workbook. @@ -2226,6 +2823,15 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getItem(name: string): Excel.NamedItem; + /** + * + * Gets a nameditem object using its name. If the nameditem object does not exist, the returned object's isNull property will be true. + * + * @param name nameditem name. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItemOrNull(name: string): Excel.NamedItem; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -2292,6 +2898,8 @@ declare namespace Excel { class Binding extends OfficeExtension.ClientObject { private m_id; private m_type; + private m_dataChanged; + private m_selectionChanged; /** * * Represents binding identifier. Read-only. @@ -2331,6 +2939,20 @@ declare namespace Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.Binding; + /** + * + * Occurs when data within the binding is changed. + * + * [Api set: ExcelApi 1.2] + */ + onDataChanged: OfficeExtension.EventHandlers; + /** + * + * Occurs when the selection is changed within the binding. + * + * [Api set: ExcelApi 1.2] + */ + onSelectionChanged: OfficeExtension.EventHandlers; } /** * @@ -2350,6 +2972,38 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ count: number; + /** + * + * Add a new binding to a particular Range. + * + * @param range Range to bind the binding to. May be an Excel Range object, or a string. If string, must contain the full address, including the sheet name + * @param bindingType Type of binding. See Excel.BindingType. + * @param id Name of binding. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + add(range: Excel.Range | string, bindingType: string, id: string): Excel.Binding; + /** + * + * Add a new binding based on a named item in the workbook. + * + * @param name Name from which to create binding. + * @param bindingType Type of binding. See Excel.BindingType. + * @param id Name of binding. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + addFromNamedItem(name: string, bindingType: string, id: string): Excel.Binding; + /** + * + * Add a new binding based on the current selection. + * + * @param bindingType Type of binding. See Excel.BindingType. + * @param id Name of binding. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + addFromSelection(bindingType: string, id: string): Excel.Binding; /** * * Gets a binding object by ID. @@ -2368,6 +3022,15 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getItemAt(index: number): Excel.Binding; + /** + * + * Gets a binding object by ID. If the binding object does not exist, the return object's isNull property will be true. + * + * @param id Id of the binding object to be retrieved. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItemOrNull(id: string): Excel.Binding; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -2419,6 +3082,15 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getItemAt(index: number): Excel.Table; + /** + * + * Gets a table by Name or ID. If the table does not exist, the return object's isNull property will be true. + * + * @param key Name or ID of the table to be retrieved. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItemOrNull(key: number | string): Excel.Table; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -2432,9 +3104,14 @@ declare namespace Excel { */ class Table extends OfficeExtension.ClientObject { private m_columns; + private m_highlightFirstColumn; + private m_highlightLastColumn; private m_id; private m_name; private m_rows; + private m_showBandedColumns; + private m_showBandedRows; + private m_showFilterButton; private m_showHeaders; private m_showTotals; private m_sort; @@ -2468,6 +3145,20 @@ declare namespace Excel { * [Api set: ExcelApi 1.2] */ worksheet: Excel.Worksheet; + /** + * + * Indicates whether the first column contains special formatting. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + highlightFirstColumn: boolean; + /** + * + * Indicates whether the last column contains special formatting. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + highlightLastColumn: boolean; /** * * Returns a value that uniquely identifies the table in a given workbook. The value of the identifier remains the same even when the table is renamed. Read-only. @@ -2482,6 +3173,27 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ name: string; + /** + * + * Indicates whether the columns show banded formatting in which odd columns are highlighted differently from even ones to make reading the table easier. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + showBandedColumns: boolean; + /** + * + * Indicates whether the rows show banded formatting in which odd rows are highlighted differently from even ones to make reading the table easier. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + showBandedRows: boolean; + /** + * + * Indicates whether the filter buttons are visible at the top of each column header. Setting this is only allowed if the table contains a header row. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + showFilterButton: boolean; /** * * Indicates whether the header row is visible or not. This value can be set to show or remove the header row. @@ -2610,6 +3322,15 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getItemAt(index: number): Excel.TableColumn; + /** + * + * Gets a column object by Name or ID. If the column does not exist, the returned object's isNull property will be true. + * + * @param key Column Name or ID. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItemOrNull(key: number | string): Excel.TableColumn; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -3131,6 +3852,16 @@ declare namespace Excel { * [Api set: ExcelApi 1.1] */ getItemAt(index: number): Excel.Chart; + /** + * + * Gets a chart using its name. If there are multiple charts with the same name, the first one will be returned. + If the chart does not exist, the returned object's isNull property will be true. + * + * @param name Name of the chart to be retrieved. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItemOrNull(name: string): Excel.Chart; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -4380,7 +5111,7 @@ declare namespace Excel { * * The first criterion used to filter data. Used as an operator in the case of "custom" filtering. For example ">50" for number greater than 50 or "=*s" for values ending in "s". - + Used as a number in the case of top/bottom items/percents. E.g. "5" for the top 5 items if filterOn is set to "topItems" * * [Api set: ExcelApi 1.2] @@ -4473,10 +5204,85 @@ declare namespace Excel { */ set: string; } + /** + * + * Represents a collection of all the PivotTables that are part of the workbook or worksheet. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + class PivotTableCollection extends OfficeExtension.ClientObject { + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Gets a PivotTable by name. + * + * @param name Name of the PivotTable to be retrieved. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItem(name: string): Excel.PivotTable; + /** + * + * Gets a PivotTable by name. If the PivotTable does not exist, the return object's isNull property will be true. + * + * @param name Name of the PivotTable to be retrieved. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + getItemOrNull(name: string): Excel.PivotTable; + /** + * + * Refreshes all the PivotTables in the collection. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + refreshAll(): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.PivotTableCollection; + } + /** + * + * Represents an Excel PivotTable. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + class PivotTable extends OfficeExtension.ClientObject { + private m_name; + private m_worksheet; + /** + * + * The worksheet containing the current PivotTable. Read-only. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + worksheet: Excel.Worksheet; + /** + * + * Name of the PivotTable. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + name: string; + /** + * + * Refreshes the PivotTable. + * + * [Api set: ExcelApi 1.3 (Preview)] + */ + refresh(): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.PivotTable; + } /** * [Api set: ExcelApi 1.1] */ - namespace BindingType { + module BindingType { var range: string; var table: string; var text: string; @@ -4484,7 +5290,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace BorderIndex { + module BorderIndex { var edgeTop: string; var edgeBottom: string; var edgeLeft: string; @@ -4497,7 +5303,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace BorderLineStyle { + module BorderLineStyle { var none: string; var continuous: string; var dash: string; @@ -4510,7 +5316,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace BorderWeight { + module BorderWeight { var hairline: string; var thin: string; var medium: string; @@ -4519,7 +5325,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace CalculationMode { + module CalculationMode { var automatic: string; var automaticExceptTables: string; var manual: string; @@ -4527,7 +5333,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace CalculationType { + module CalculationType { var recalculate: string; var full: string; var fullRebuild: string; @@ -4535,7 +5341,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace ClearApplyTo { + module ClearApplyTo { var all: string; var formats: string; var contents: string; @@ -4543,7 +5349,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace ChartDataLabelPosition { + module ChartDataLabelPosition { var invalid: string; var none: string; var center: string; @@ -4560,7 +5366,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace ChartLegendPosition { + module ChartLegendPosition { var invalid: string; var top: string; var bottom: string; @@ -4570,9 +5376,17 @@ declare namespace Excel { var custom: string; } /** + * + * Specifies whether the series are by rows or by columns. On Desktop, the "auto" option will inspect the source data shape to automatically guess whether the data is by rows or columns; on Excel Online, "auto" will simply default to "columns". + * * [Api set: ExcelApi 1.1] */ - namespace ChartSeriesBy { + module ChartSeriesBy { + /** + * + * On Desktop, the "auto" option will inspect the source data shape to automatically guess whether the data is by rows or columns; on Excel Online, "auto" will simply default to "columns". + * + */ var auto: string; var columns: string; var rows: string; @@ -4580,7 +5394,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace ChartType { + module ChartType { var invalid: string; var columnClustered: string; var columnStacked: string; @@ -4659,21 +5473,21 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace ChartUnderlineStyle { + module ChartUnderlineStyle { var none: string; var single: string; } /** * [Api set: ExcelApi 1.1] */ - namespace DeleteShiftDirection { + module DeleteShiftDirection { var up: string; var left: string; } /** * [Api set: ExcelApi 1.2] */ - namespace DynamicFilterCriteria { + module DynamicFilterCriteria { var unknown: string; var aboveAverage: string; var allDatesInPeriodApril: string; @@ -4713,7 +5527,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.2] */ - namespace FilterDatetimeSpecificity { + module FilterDatetimeSpecificity { var year: string; var month: string; var day: string; @@ -4724,7 +5538,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.2] */ - namespace FilterOn { + module FilterOn { var bottomItems: string; var bottomPercent: string; var cellColor: string; @@ -4739,14 +5553,14 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.2] */ - namespace FilterOperator { + module FilterOperator { var and: string; var or: string; } /** * [Api set: ExcelApi 1.1] */ - namespace HorizontalAlignment { + module HorizontalAlignment { var general: string; var left: string; var center: string; @@ -4759,7 +5573,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.2] */ - namespace IconSet { + module IconSet { var invalid: string; var threeArrows: string; var threeArrowsGray: string; @@ -4785,7 +5599,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.2] */ - namespace ImageFittingMode { + module ImageFittingMode { var fit: string; var fitAndCenter: string; var fill: string; @@ -4793,14 +5607,14 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace InsertShiftDirection { + module InsertShiftDirection { var down: string; var right: string; } /** * [Api set: ExcelApi 1.1] */ - namespace NamedItemType { + module NamedItemType { var string: string; var integer: string; var double: string; @@ -4810,7 +5624,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace RangeUnderlineStyle { + module RangeUnderlineStyle { var none: string; var single: string; var double: string; @@ -4820,7 +5634,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace SheetVisibility { + module SheetVisibility { var visible: string; var hidden: string; var veryHidden: string; @@ -4828,7 +5642,7 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.1] */ - namespace RangeValueType { + module RangeValueType { var unknown: string; var empty: string; var string: string; @@ -4840,14 +5654,14 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.2] */ - namespace SortOrientation { + module SortOrientation { var rows: string; var columns: string; } /** * [Api set: ExcelApi 1.2] */ - namespace SortOn { + module SortOn { var value: string; var cellColor: string; var fontColor: string; @@ -4856,21 +5670,21 @@ declare namespace Excel { /** * [Api set: ExcelApi 1.2] */ - namespace SortDataOption { + module SortDataOption { var normal: string; var textAsNumber: string; } /** * [Api set: ExcelApi 1.2] */ - namespace SortMethod { + module SortMethod { var pinYin: string; var strokeCount: string; } /** * [Api set: ExcelApi 1.1] */ - namespace VerticalAlignment { + module VerticalAlignment { var top: string; var center: string; var bottom: string; @@ -8229,6 +9043,57 @@ declare namespace Excel { * [Api set: ExcelApi 1.2] */ tbillYield(settlement: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, maturity: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult, pr: number | string | boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; + /** + * + * Returns the left-tailed Student's t-distribution. + * + * @param x Is the numeric value at which to evaluate the distribution. + * @param degFreedom Is an integer indicating the number of degrees of freedom that characterize the distribution. + * @param cumulative Is a logical value: for the cumulative distribution function, use TRUE; for the probability density function, use FALSE. + * + * [Api set: ExcelApi 1.2] + */ + t_Dist(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, cumulative: boolean | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; + /** + * + * Returns the two-tailed Student's t-distribution. + * + * @param x Is the numeric value at which to evaluate the distribution. + * @param degFreedom Is an integer indicating the number of degrees of freedom that characterize the distribution. + * + * [Api set: ExcelApi 1.2] + */ + t_Dist_2T(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; + /** + * + * Returns the right-tailed Student's t-distribution. + * + * @param x Is the numeric value at which to evaluate the distribution. + * @param degFreedom Is an integer indicating the number of degrees of freedom that characterize the distribution. + * + * [Api set: ExcelApi 1.2] + */ + t_Dist_RT(x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; + /** + * + * Returns the left-tailed inverse of the Student's t-distribution. + * + * @param probability Is the probability associated with the two-tailed Student's t-distribution, a number between 0 and 1 inclusive. + * @param degFreedom Is a positive integer indicating the number of degrees of freedom to characterize the distribution. + * + * [Api set: ExcelApi 1.2] + */ + t_Inv(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; + /** + * + * Returns the two-tailed inverse of the Student's t-distribution. + * + * @param probability Is the probability associated with the two-tailed Student's t-distribution, a number between 0 and 1 inclusive. + * @param degFreedom Is a positive integer indicating the number of degrees of freedom to characterize the distribution. + * + * [Api set: ExcelApi 1.2] + */ + t_Inv_2T(probability: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, degFreedom: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; /** * * Returns the tangent of an angle. @@ -8598,7 +9463,7 @@ declare namespace Excel { */ z_Test(array: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, sigma?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; } - namespace ErrorCodes { + module ErrorCodes { var accessDenied: string; var generalException: string; var insertDeleteConflict: string; @@ -8613,7 +9478,7 @@ declare namespace Excel { var unsupportedOperation: string; } } -declare namespace Excel { +declare module Excel { /** * The RequestContext object facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the request context is required to get access to the Excel object model from the add-in. */ @@ -8646,10 +9511,6 @@ declare namespace Word { * [Api set: WordApiDesktop 1.3 Beta] */ createDocument(base64File?: string): Word.Document; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Create a new instance of Word.Application object */ @@ -8751,13 +9612,6 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ type: string; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Clears the contents of the body object. The user can perform the undo operation on the cleared content. @@ -8905,16 +9759,10 @@ declare namespace Word { * [Api set: WordApi 1.1] */ select(selectionMode?: string): void; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.Body; - _initReferenceId(value: string): void; } /** * @@ -9100,13 +9948,6 @@ declare namespace Word { * [Api set: WordApi 1.1] */ type: string; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Clears the contents of the content control. The user can perform the undo operation on the cleared content. @@ -9278,16 +10119,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ split(delimiters: Array, multiParagraphs?: boolean, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.ContentControl; - _initReferenceId(value: string): void; } /** * @@ -9308,13 +10143,6 @@ declare namespace Word { first: Word.ContentControl; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Gets a content control by its identifier. @@ -9360,16 +10188,10 @@ declare namespace Word { * [Api set: WordApi 1.1] */ getItem(index: number): Word.ContentControl; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.ContentControlCollection; - _initReferenceId(value: string): void; } /** * @@ -9411,13 +10233,6 @@ declare namespace Word { * [Api set: WordApi 1.1] */ saved: boolean; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Gets the current selection of the document. Multiple selections are not supported. @@ -9439,20 +10254,10 @@ declare namespace Word { * [Api set: WordApi 1.1] */ save(): void; - _GetObjectByReferenceId(referenceId: string): OfficeExtension.ClientResult; - _GetObjectTypeNameByReferenceId(referenceId: string): OfficeExtension.ClientResult; - _KeepReference(): void; - _RemoveAllReferences(): void; - _RemoveReference(referenceId: string): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.Document; - _initReferenceId(value: string): void; } /** * @@ -9550,23 +10355,10 @@ declare namespace Word { * [Api set: WordApi 1.1] */ underline: string; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.Font; - _initReferenceId(value: string): void; } /** * @@ -9673,20 +10465,6 @@ declare namespace Word { * [Api set: WordApi 1.1] */ width: number; - /** - * - * ID - * - * [Api set: WordApi] - */ - _Id: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Deletes the inline picture from the document. @@ -9796,16 +10574,10 @@ declare namespace Word { * [Api set: WordApi 1.2] */ select(selectionMode?: string): void; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.InlinePicture; - _initReferenceId(value: string): void; } /** * @@ -9826,32 +10598,10 @@ declare namespace Word { first: Word.InlinePicture; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets an inline picture object by its index in the collection. - * - * @param index A number that identifies the index location of an inline picture object. - * - * [Api set: WordApi 1.1] - */ - _GetItem(index: number): Word.InlinePicture; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.InlinePictureCollection; - _initReferenceId(value: string): void; } /** * @@ -9877,7 +10627,6 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ id: number; - _ReferenceId: string; /** * * Gets the paragraphs in the list. @@ -9897,16 +10646,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.List; - _initReferenceId(value: string): void; } /** * @@ -9927,7 +10670,6 @@ declare namespace Word { first: Word.List; /** Gets the loaded child items in this collection. */ items: Array; - _ReferenceId: string; /** * * Gets a list by its identifier. @@ -9937,25 +10679,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ getById(id: number): Word.List; - /** - * - * Gets a list object by its index in the collection. - * - * @param index A number that identifies the index location of a list object. - * - * [Api set: WordApi 1.3 Beta] - */ - _GetItem(index: number): Word.List; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.ListCollection; - _initReferenceId(value: string): void; } /** * @@ -9973,17 +10700,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ levelTypes: Array; - _ReferenceId: string; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.ListFormat; - _initReferenceId(value: string): void; } /** * @@ -10009,7 +10729,6 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ siblingIndex: number; - _ReferenceId: string; /** * * Gets the list item parent, or the closest ancestor if the parent does not exist. @@ -10028,16 +10747,10 @@ declare namespace Word { * [Api set: WordApiDesktop 1.3 Beta] */ getDescendants(directChildrenOnly?: boolean): Word.ParagraphCollection; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.ListItem; - _initReferenceId(value: string): void; } /** * @@ -10248,20 +10961,6 @@ declare namespace Word { * [Api set: WordApi 1.1] */ text: string; - /** - * - * ID - * - * [Api set: WordApi] - */ - _Id: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Clears the contents of the paragraph object. The user can perform the undo operation on the cleared content. @@ -10444,16 +11143,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ startNewList(): Word.List; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.Paragraph; - _initReferenceId(value: string): void; } /** * @@ -10482,32 +11175,10 @@ declare namespace Word { last: Word.Paragraph; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets a paragraph object by its index in the collection. - * - * @param index A number that identifies the index location of a paragraph object. - * - * [Api set: WordApi 1.1] - */ - _GetItem(index: number): Word.Paragraph; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.ParagraphCollection; - _initReferenceId(value: string): void; } /** * @@ -10630,20 +11301,6 @@ declare namespace Word { * [Api set: WordApi 1.1] */ text: string; - /** - * - * ID - * - * [Api set: WordApi] - */ - _Id: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Clears the contents of the range object. The user can perform the undo operation on the cleared content. @@ -10864,16 +11521,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ split(delimiters: Array, multiParagraphs?: boolean, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.Range; - _initReferenceId(value: string): void; } /** * @@ -10894,32 +11545,10 @@ declare namespace Word { first: Word.Range; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets a range object by its index in the collection. - * - * @param index A number that identifies the index location of a range object. - * - * [Api set: WordApi 1.3 Beta] - */ - _GetItem(index: number): Word.Range; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.RangeCollection; - _initReferenceId(value: string): void; } /** * @@ -10993,10 +11622,6 @@ declare namespace Word { * [Api set: WordApi 1.1] */ matchWildcards: boolean; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -11025,32 +11650,10 @@ declare namespace Word { first: Word.Range; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets a range object by its index in the collection. - * - * @param index A number that identifies the index location of a range object. - * - * [Api set: WordApi 1.1] - */ - _GetItem(index: number): Word.Range; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.SearchResultCollection; - _initReferenceId(value: string): void; } /** * @@ -11077,20 +11680,6 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ next: Word.Section; - /** - * - * ID - * - * [Api set: WordApi] - */ - _Id: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Gets one of the section's footers. @@ -11109,16 +11698,10 @@ declare namespace Word { * [Api set: WordApi 1.1] */ getHeader(type: string): Word.Body; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.Section; - _initReferenceId(value: string): void; } /** * @@ -11139,32 +11722,10 @@ declare namespace Word { first: Word.Section; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets a section object by its index in the collection. - * - * @param index A number that identifies the index location of a section object. - * - * [Api set: WordApi 1.1] - */ - _GetItem(index: number): Word.Section; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.SectionCollection; - _initReferenceId(value: string): void; } /** * @@ -11399,20 +11960,6 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ width: number; - /** - * - * ID - * - * [Api set: WordApi] - */ - _Id: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Adds columns to the start or end of the table, using the first or last existing column as a template. This is applicable to uniform tables. The string values, if specified, are set in the newly inserted rows. @@ -11594,16 +12141,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ select(selectionMode?: string): void; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.Table; - _initReferenceId(value: string): void; } /** * @@ -11624,32 +12165,10 @@ declare namespace Word { first: Word.Table; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets a table object by its index in the collection. - * - * @param index A number that identifies the index location of a table object. - * - * [Api set: WordApi 1.3 Beta] - */ - _GetItem(index: number): Word.Table; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.TableCollection; - _initReferenceId(value: string): void; } /** * @@ -11780,20 +12299,6 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ verticalAlignment: string; - /** - * - * ID - * - * [Api set: WordApi] - */ - _Id: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Clears the contents of the row. @@ -11863,16 +12368,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ select(selectionMode?: string): void; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.TableRow; - _initReferenceId(value: string): void; } /** * @@ -11893,32 +12392,10 @@ declare namespace Word { first: Word.TableRow; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets a table row object by its index in the collection. - * - * @param index A number that identifies the index location of a table row object. - * - * [Api set: WordApi 1.3 Beta] - */ - _GetItem(index: number): Word.TableRow; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.TableRowCollection; - _initReferenceId(value: string): void; } /** * @@ -12049,20 +12526,6 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ width: number; - /** - * - * ID - * - * [Api set: WordApi] - */ - _Id: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; /** * * Deletes the column containing this cell. This is applicable to uniform tables. @@ -12118,16 +12581,10 @@ declare namespace Word { * [Api set: WordApiDesktop 1.3 Beta] */ split(rowCount: number, columnCount: number): void; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.TableCell; - _initReferenceId(value: string): void; } /** * @@ -12148,32 +12605,10 @@ declare namespace Word { first: Word.TableCell; /** Gets the loaded child items in this collection. */ items: Array; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - /** - * - * Gets a table cell object by its index in the collection. - * - * @param index A number that identifies the index location of a table cell object. - * - * [Api set: WordApi 1.3 Beta] - */ - _GetItem(index: number): Word.TableCell; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.TableCellCollection; - _initReferenceId(value: string): void; } /** * @@ -12207,23 +12642,10 @@ declare namespace Word { * [Api set: WordApi 1.3 Beta] */ width: number; - /** - * - * ReferenceId - * - * [Api set: WordApi] - */ - _ReferenceId: string; - _KeepReference(): void; - /** Handle results returned from the document - * @private - */ - _handleResult(value: any): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Word.TableBorderStyle; - _initReferenceId(value: string): void; } /** * From 3f9c7fe3d2469467341d43af6d81c2e530324869 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Patrick=20Bu=C3=9Fmann?= Date: Sat, 13 Aug 2016 19:55:05 +0200 Subject: [PATCH 033/844] Added support for plupload --- plupload/plupload-tests.ts | 1 + plupload/plupload.d.ts | 197 +++++++++++++++++++++++++++++++++++++ 2 files changed, 198 insertions(+) create mode 100644 plupload/plupload-tests.ts create mode 100644 plupload/plupload.d.ts diff --git a/plupload/plupload-tests.ts b/plupload/plupload-tests.ts new file mode 100644 index 0000000000..a7348c0ffc --- /dev/null +++ b/plupload/plupload-tests.ts @@ -0,0 +1 @@ +/// diff --git a/plupload/plupload.d.ts b/plupload/plupload.d.ts new file mode 100644 index 0000000000..fddef3d497 --- /dev/null +++ b/plupload/plupload.d.ts @@ -0,0 +1,197 @@ +// Type definitions for Plupload 2 +// Project: http://www.plupload.com/ +// Definitions by: Patrick Bußmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface plupload_settings { + /** Required Options */ + browse_button: any, + url: string, + + /** Filters */ + filters?: plupload_filters, + + /** Control the request */ + headers?: any; + max_retries?: number; + multipart?: boolean; + multipart_params?: any; + + /** Chunk */ + chunk_size?: number|string; + + /** Client-Side Image Resize */ + resize?: plupload_resize; + + /** Drag&Drop Files from the Desktop */ + drop_element?: string; + + /** Useful Options */ + multi_selection?: boolean; + required_features?: string|any; + unique_names?: boolean; + + /** Optional */ + runtimes?: string; + file_data_name?: string; + container?: any; + flash_swf_url?: string; + silverlight_xap_url?: string; + + /** Events */ + init?: plupload_events; +} + +interface plupload_filters { + mime_types?: plupload_filters_mime_types[]; + max_file_size?: number|string; + prevent_duplicates?: boolean; +} + +interface plupload_filters_mime_types { + title: string; + extensions: string; +} + +interface plupload_resize { + width?: number; + height?: number; + crop?: boolean; + quality?: number; + preserve_headers?: boolean; +} + +interface plupload_queue_progress { + size: number; + loaded: number; + uploaded: number; + failed: number; + queued: number; + percent: number; + bytesPerSec: number; + reset(): void; +} + +interface plupload_event { + (uploader: plupload): any; +} + +interface plupload_event_file { + (uploader: plupload, file: any): any; +} + +interface plupload_event_files { + (uploader: plupload, files: any[]): any; +} + +interface plupload_event_OptionChanged { + (uploader: plupload, name: string, value: any, oldValue: any): any; +} + +interface plupload_event_FileUploaded { + (uploader: plupload, file: any, response: plupload_response): any; +} + +interface plupload_event_ChunkUploaded { + (uploader: plupload, file: any, response: plupload_chunk_response): any; +} + +interface plupload_event_Error { + (uploader: plupload, error: plupload_error): any; +} + +interface plupload_events { + Init?: plupload_event; + PostInit?: plupload_event; + OptionChanged?: plupload_event_OptionChanged; + Refresh?: plupload_event; + StateChanged?: plupload_event; + UploadFile?: plupload_event_file; + BeforeUpload?: plupload_event_file; + QueueChanged?: plupload_event; + UploadProgress?: plupload_event_file; + FilesRemoved?: plupload_event_files; + FileFiltered?: plupload_event_file; + FilesAdded?: plupload_event_files; + FileUploaded?: plupload_event_FileUploaded; + ChunkUploaded?: plupload_event_ChunkUploaded; + UploadComplete?: plupload_event_files; + Error?: plupload_event_Error; + Destroy?: plupload_event; +} + +interface plupload_response { + response: string; + status: number; + responseHeaders: string; +} + +interface plupload_chunk_response extends plupload_response { + offset: number; + total: number; +} + +interface plupload_error extends plupload_response { + code: number; + message: string; + file: any; +} + +declare class plupload { + static Uploader(settings: plupload_settings):void; + + static VERSION: string; + + static STOPPED: number; + static STARTED: number; + static QUEUED: number; + static UPLOADING: number; + static FAILED: number; + static DONE: number; + static GENERIC_ERROR: number; + static HTTP_ERROR: number; + static IO_ERROR: number; + static SECURITY_ERROR: number; + static INIT_ERROR: number; + static FILE_SIZE_ERROR: number; + static FILE_EXTENSION_ERROR: number; + static FILE_DUPLICATE_ERROR: number; + static IMAGE_FORMAT_ERROR: number; + static MEMORY_ERROR: number; + static IMAGE_DIMENSIONS_ERROR: number; + + static mimeTypes: any; + static ua: any; + + static typeOf(o: any): string; + static extend(target: any): any; + static guid(guid: string): string; + + /** Properties */ + id: string; + state: number; + features: string; + runtime: string; + files: any; + settings: any; + total: plupload_queue_progress; + + /** Methods */ + init(): any; + setOption(option: string|any, value?: any): any; + getOption(option?: string): any; + refresh(): any; + start(): any; + stop(): any; + disableBrowse(disable: boolean): any; + getFile(id: string): any; + addFile(file: any, fileName?: string): any; + removeFile(file: any): any; + splice(start?: number, length?: number): any; + trigger(name: string, Multiple: any): any; + hasEventListener(name: string): any; + bind(name: string, func: any, scope: any): any; + unbind(name: string, func: any): any; + unbindAll(): any; + destroy(): any; +} From 08f9659a3b4a2d2cad90cc50639279ec1372fcb5 Mon Sep 17 00:00:00 2001 From: Mattijs Kneppers Date: Mon, 15 Aug 2016 17:45:45 +0200 Subject: [PATCH 034/844] clean: remove glMatrix definition (it is only used internally) and add space after every colon --- gl-matrix/gl-matrix-typed-tests.ts | 3 +- gl-matrix/gl-matrix-typed.d.ts | 296 ++++++++++++++--------------- 2 files changed, 144 insertions(+), 155 deletions(-) diff --git a/gl-matrix/gl-matrix-typed-tests.ts b/gl-matrix/gl-matrix-typed-tests.ts index 7364ec0a83..361690b5e7 100644 --- a/gl-matrix/gl-matrix-typed-tests.ts +++ b/gl-matrix/gl-matrix-typed-tests.ts @@ -1,8 +1,7 @@ /// // common -import {vec2, mat2, mat3, mat4, vec3, vec4, glMatrix, mat2d, quat} from "./gl-matrix-typed"; -var result: number = glMatrix.toRadian(180); +import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "./gl-matrix-typed"; var outVal: number; var outBool: boolean; diff --git a/gl-matrix/gl-matrix-typed.d.ts b/gl-matrix/gl-matrix-typed.d.ts index e172074fec..1309e994c8 100644 --- a/gl-matrix/gl-matrix-typed.d.ts +++ b/gl-matrix/gl-matrix-typed.d.ts @@ -3,16 +3,6 @@ // Definitions by: Mattijs Kneppers , based on definitions by Tat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Common -export class glMatrix { - /** - * Convert Degree To Radian - * - * @param a Angle in Degrees - */ - public static toRadian(a: number): number; -} - // vec2 export class vec2 extends Float32Array { private typeVec2:number; @@ -137,7 +127,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to ceil * @returns {vec2} out */ - public static ceil(out:vec2, a:vec2):vec2; + public static ceil(out: vec2, a: vec2): vec2; /** * Math.floor the components of a vec2 @@ -146,7 +136,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to floor * @returns {vec2} out */ - public static floor (out:vec2, a:vec2):vec2; + public static floor (out: vec2, a: vec2): vec2; /** * Returns the minimum of two vec2's @@ -175,7 +165,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to round * @returns {vec2} out */ - public static round(out:vec2, a:vec2):vec2; + public static round(out: vec2, a: vec2): vec2; /** @@ -427,7 +417,7 @@ export class vec2 extends Float32Array { * @param {vec2} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a:vec2, b:vec2): boolean; + public static exactEquals (a: vec2, b: vec2): boolean; /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -436,7 +426,7 @@ export class vec2 extends Float32Array { * @param {vec2} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a:vec2, b:vec2) : boolean; + public static equals (a: vec2, b: vec2) : boolean; } // vec3 @@ -565,7 +555,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to ceil * @returns {vec3} out */ - public static ceil (out:vec3, a:vec3) : vec3; + public static ceil (out: vec3, a: vec3) : vec3; /** * Math.floor the components of a vec3 @@ -574,7 +564,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to floor * @returns {vec3} out */ - public static floor (out:vec3, a:vec3) :vec3; + public static floor (out: vec3, a: vec3) : vec3; /** * Returns the minimum of two vec3's @@ -603,7 +593,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to round * @returns {vec3} out */ - public static round (out:vec3, a:vec3) : vec3 + public static round (out: vec3, a: vec3) : vec3 /** * Scales a vec3 by a scalar number @@ -762,7 +752,7 @@ export class vec3 extends Float32Array { * @param {number} t interpolation amount between the two inputs * @returns {vec3} out */ - public static hermite (out:vec3, a:vec3, b:vec3, c:vec3, d:vec3, t:number) : vec3; + public static hermite (out: vec3, a: vec3, b: vec3, c: vec3, d: vec3, t:number) : vec3; /** * Performs a bezier interpolation with two control points @@ -775,7 +765,7 @@ export class vec3 extends Float32Array { * @param {number} t interpolation amount between the two inputs * @returns {vec3} out */ - public static bezier (out:vec3, a:vec3, b:vec3, c:vec3, d:vec3, t:number) :vec3; + public static bezier (out: vec3, a: vec3, b: vec3, c: vec3, d: vec3, t:number) : vec3; /** * Generates a random unit vector @@ -908,7 +898,7 @@ export class vec3 extends Float32Array { * @param {vec3} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a:vec3, b:vec3): boolean + public static exactEquals (a: vec3, b: vec3): boolean /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -917,7 +907,7 @@ export class vec3 extends Float32Array { * @param {vec3} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a:vec3, b:vec3) : boolean + public static equals (a: vec3, b: vec3) : boolean } // vec4 @@ -1048,7 +1038,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to ceil * @returns {vec4} out */ - public static ceil (out:vec4, a:vec4) : vec4; + public static ceil (out: vec4, a: vec4) : vec4; /** * Math.floor the components of a vec4 @@ -1057,7 +1047,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to floor * @returns {vec4} out */ - public static floor (out:vec4, a:vec4) : vec4; + public static floor (out: vec4, a: vec4) : vec4; /** * Returns the minimum of two vec4's @@ -1086,7 +1076,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to round * @returns {vec4} out */ - public static round (out:vec4, a:vec4): vec4; + public static round (out: vec4, a: vec4): vec4; /** * Scales a vec4 by a scalar number @@ -1306,7 +1296,7 @@ export class vec4 extends Float32Array { * @param {vec4} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a:vec4, b:vec4) : boolean; + public static exactEquals (a: vec4, b: vec4) : boolean; /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -1315,7 +1305,7 @@ export class vec4 extends Float32Array { * @param {vec4} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a:vec4, b:vec4) : boolean; + public static equals (a: vec4, b: vec4) : boolean; } // mat2 @@ -1327,7 +1317,7 @@ export class mat2 extends Float32Array { * * @returns a new 2x2 matrix */ - public static create():mat2; + public static create(): mat2; /** * Creates a new mat2 initialized with values from an existing matrix @@ -1335,7 +1325,7 @@ export class mat2 extends Float32Array { * @param a matrix to clone * @returns a new 2x2 matrix */ - public static clone(a:mat2):mat2; + public static clone(a: mat2): mat2; /** * Copy the values from one mat2 to another @@ -1344,7 +1334,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns out */ - public static copy(out:mat2, a:mat2):mat2; + public static copy(out: mat2, a: mat2): mat2; /** * Set a mat2 to the identity matrix @@ -1352,7 +1342,7 @@ export class mat2 extends Float32Array { * @param out the receiving matrix * @returns out */ - public static identity(out:mat2):mat2; + public static identity(out: mat2): mat2; /** * Create a new mat2 with the given values @@ -1363,7 +1353,7 @@ export class mat2 extends Float32Array { * @param {number} m11 Component in column 1, row 1 position (index 3) * @returns {mat2} out A new 2x2 matrix */ - public static fromValues(m00:number, m01:number, m10:number, m11:number):mat2; + public static fromValues(m00:number, m01:number, m10:number, m11:number): mat2; /** * Set the components of a mat2 to the given values @@ -1375,7 +1365,7 @@ export class mat2 extends Float32Array { * @param {number} m11 Component in column 1, row 1 position (index 3) * @returns {mat2} out */ - public static set(out:mat2, m00:number, m01:number, m10:number, m11:number):mat2; + public static set(out: mat2, m00:number, m01:number, m10:number, m11:number): mat2; /** * Transpose the values of a mat2 @@ -1384,7 +1374,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns out */ - public static transpose(out:mat2, a:mat2):mat2; + public static transpose(out: mat2, a: mat2): mat2; /** * Inverts a mat2 @@ -1393,7 +1383,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns out */ - public static invert(out:mat2, a:mat2):mat2; + public static invert(out: mat2, a: mat2): mat2; /** * Calculates the adjugate of a mat2 @@ -1402,7 +1392,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns out */ - public static adjoint(out:mat2, a:mat2):mat2; + public static adjoint(out: mat2, a: mat2): mat2; /** * Calculates the determinant of a mat2 @@ -1410,7 +1400,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a:mat2):number; + public static determinant(a: mat2):number; /** * Multiplies two mat2's @@ -1420,7 +1410,7 @@ export class mat2 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out:mat2, a:mat2, b:mat2):mat2; + public static multiply(out: mat2, a: mat2, b: mat2): mat2; /** * Multiplies two mat2's @@ -1430,7 +1420,7 @@ export class mat2 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out:mat2, a:mat2, b:mat2):mat2; + public static mul(out: mat2, a: mat2, b: mat2): mat2; /** * Rotates a mat2 by the given angle @@ -1440,7 +1430,7 @@ export class mat2 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotate(out:mat2, a:mat2, rad:number):mat2; + public static rotate(out: mat2, a: mat2, rad:number): mat2; /** * Scales the mat2 by the dimensions in the given vec2 @@ -1450,7 +1440,7 @@ export class mat2 extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out:mat2, a:mat2, v:vec2):mat2; + public static scale(out: mat2, a: mat2, v: vec2): mat2; /** * Creates a matrix from a given angle @@ -1463,7 +1453,7 @@ export class mat2 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat2} out */ - public static fromRotation(out:mat2, rad:number):mat2; + public static fromRotation(out: mat2, rad:number): mat2; /** * Creates a matrix from a vector scaling @@ -1476,7 +1466,7 @@ export class mat2 extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat2} out */ - public static fromScaling(out:mat2, v:vec2):mat2; + public static fromScaling(out: mat2, v: vec2): mat2; /** * Returns a string representation of a mat2 @@ -1484,7 +1474,7 @@ export class mat2 extends Float32Array { * @param a matrix to represent as a string * @returns string representation of the matrix */ - public static str(a:mat2):string; + public static str(a: mat2):string; /** * Returns Frobenius norm of a mat2 @@ -1492,7 +1482,7 @@ export class mat2 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a:mat2):number; + public static frob(a: mat2):number; /** * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix @@ -1501,7 +1491,7 @@ export class mat2 extends Float32Array { * @param U the upper triangular matrix * @param a the input matrix to factorize */ - public static LDU(L:mat2, D:mat2, U:mat2, a:mat2):mat2; + public static LDU(L: mat2, D: mat2, U: mat2, a: mat2): mat2; /** * Adds two mat2's @@ -1511,7 +1501,7 @@ export class mat2 extends Float32Array { * @param {mat2} b the second operand * @returns {mat2} out */ - public static add(out:mat2, a:mat2, b:mat2):mat2; + public static add(out: mat2, a: mat2, b: mat2): mat2; /** * Subtracts matrix b from matrix a @@ -1521,7 +1511,7 @@ export class mat2 extends Float32Array { * @param {mat2} b the second operand * @returns {mat2} out */ - public static subtract (out:mat2, a:mat2, b:mat2):mat2; + public static subtract (out: mat2, a: mat2, b: mat2): mat2; /** * Subtracts matrix b from matrix a @@ -1531,7 +1521,7 @@ export class mat2 extends Float32Array { * @param {mat2} b the second operand * @returns {mat2} out */ - public static sub (out:mat2, a:mat2, b:mat2):mat2; + public static sub (out: mat2, a: mat2, b: mat2): mat2; /** * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) @@ -1540,7 +1530,7 @@ export class mat2 extends Float32Array { * @param {mat2} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals (a:mat2, b:mat2):boolean; + public static exactEquals (a: mat2, b: mat2):boolean; /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -1549,7 +1539,7 @@ export class mat2 extends Float32Array { * @param {mat2} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals (a:mat2, b:mat2) :boolean; + public static equals (a: mat2, b: mat2) :boolean; /** * Multiply each element of the matrix by a scalar. @@ -1559,7 +1549,7 @@ export class mat2 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat2} out */ - public static multiplyScalar (out:mat2, a:mat2, b:number) :mat2 + public static multiplyScalar (out: mat2, a: mat2, b:number) : mat2 /** * Adds two mat2's after multiplying each element of the second operand by a scalar value. @@ -1570,7 +1560,7 @@ export class mat2 extends Float32Array { * @param {number} scale the amount to scale b's elements by before adding * @returns {mat2} out */ - public static multiplyScalarAndAdd (out:mat2, a:mat2, b:mat2, scale:number): mat2 + public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale:number): mat2 @@ -1638,7 +1628,7 @@ export class mat2d extends Float32Array { * @param {number} ty Component TY (index 5) * @returns {mat2d} out */ - public static set (out:mat2d, a:number, b:number, c:number, d:number, tx:number, ty:number) :mat2d + public static set (out: mat2d, a:number, b:number, c:number, d:number, tx:number, ty:number) : mat2d /** * Inverts a mat2d @@ -1718,7 +1708,7 @@ export class mat2d extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat2d} out */ - public static fromRotation (out:mat2d, rad:number): mat2d; + public static fromRotation (out: mat2d, rad:number): mat2d; /** * Creates a matrix from a vector scaling @@ -1731,7 +1721,7 @@ export class mat2d extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat2d} out */ - public static fromScaling (out:mat2d, v:vec2):mat2d; + public static fromScaling (out: mat2d, v: vec2): mat2d; /** * Creates a matrix from a vector translation @@ -1744,7 +1734,7 @@ export class mat2d extends Float32Array { * @param {vec2} v Translation vector * @returns {mat2d} out */ - public static fromTranslation (out:mat2d, v:vec2):mat2d + public static fromTranslation (out: mat2d, v: vec2): mat2d /** * Returns a string representation of a mat2d @@ -1841,7 +1831,7 @@ export class mat3 extends Float32Array { * * @returns a new 3x3 matrix */ - public static create():mat3; + public static create(): mat3; /** * Copies the upper-left 3x3 values into the given mat3. @@ -1850,7 +1840,7 @@ export class mat3 extends Float32Array { * @param {mat4} a the source 4x4 matrix * @returns {mat3} out */ - public static fromMat4(out:mat3, a:mat4):mat3 + public static fromMat4(out: mat3, a: mat4): mat3 /** * Creates a new mat3 initialized with values from an existing matrix @@ -1858,7 +1848,7 @@ export class mat3 extends Float32Array { * @param a matrix to clone * @returns a new 3x3 matrix */ - public static clone(a:mat3):mat3; + public static clone(a: mat3): mat3; /** * Copy the values from one mat3 to another @@ -1867,7 +1857,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns out */ - public static copy(out:mat3, a:mat3):mat3; + public static copy(out: mat3, a: mat3): mat3; /** * Create a new mat3 with the given values @@ -1883,7 +1873,7 @@ export class mat3 extends Float32Array { * @param {number} m22 Component in column 2, row 2 position (index 8) * @returns {mat3} A new mat3 */ - public static fromValues(m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number):mat3; + public static fromValues(m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number): mat3; /** @@ -1901,7 +1891,7 @@ export class mat3 extends Float32Array { * @param {number} m22 Component in column 2, row 2 position (index 8) * @returns {mat3} out */ - public static set(out:mat3, m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number):mat3 + public static set(out: mat3, m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number): mat3 /** * Set a mat3 to the identity matrix @@ -1909,7 +1899,7 @@ export class mat3 extends Float32Array { * @param out the receiving matrix * @returns out */ - public static identity(out:mat3):mat3; + public static identity(out: mat3): mat3; /** * Transpose the values of a mat3 @@ -1918,7 +1908,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns out */ - public static transpose(out:mat3, a:mat3):mat3; + public static transpose(out: mat3, a: mat3): mat3; /** * Inverts a mat3 @@ -1927,7 +1917,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns out */ - public static invert(out:mat3, a:mat3):mat3; + public static invert(out: mat3, a: mat3): mat3; /** * Calculates the adjugate of a mat3 @@ -1936,7 +1926,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns out */ - public static adjoint(out:mat3, a:mat3):mat3; + public static adjoint(out: mat3, a: mat3): mat3; /** * Calculates the determinant of a mat3 @@ -1944,7 +1934,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a:mat3):number; + public static determinant(a: mat3):number; /** * Multiplies two mat3's @@ -1954,7 +1944,7 @@ export class mat3 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out:mat3, a:mat3, b:mat3):mat3; + public static multiply(out: mat3, a: mat3, b: mat3): mat3; /** * Multiplies two mat3's @@ -1964,7 +1954,7 @@ export class mat3 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out:mat3, a:mat3, b:mat3):mat3; + public static mul(out: mat3, a: mat3, b: mat3): mat3; /** @@ -1975,7 +1965,7 @@ export class mat3 extends Float32Array { * @param v vector to translate by * @returns out */ - public static translate(out:mat3, a:mat3, v:vec3):mat3; + public static translate(out: mat3, a: mat3, v: vec3): mat3; /** * Rotates a mat3 by the given angle @@ -1985,7 +1975,7 @@ export class mat3 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotate(out:mat3, a:mat3, rad:number):mat3; + public static rotate(out: mat3, a: mat3, rad:number): mat3; /** * Scales the mat3 by the dimensions in the given vec2 @@ -1995,7 +1985,7 @@ export class mat3 extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out:mat3, a:mat3, v:vec2):mat3; + public static scale(out: mat3, a: mat3, v: vec2): mat3; /** * Creates a matrix from a vector translation @@ -2008,7 +1998,7 @@ export class mat3 extends Float32Array { * @param {vec2} v Translation vector * @returns {mat3} out */ - public static fromTranslation(out:mat3, v:vec2):mat3 + public static fromTranslation(out: mat3, v: vec2): mat3 /** * Creates a matrix from a given angle @@ -2021,7 +2011,7 @@ export class mat3 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat3} out */ - public static fromRotation(out:mat3, rad:number):mat3 + public static fromRotation(out: mat3, rad:number): mat3 /** * Creates a matrix from a vector scaling @@ -2034,7 +2024,7 @@ export class mat3 extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat3} out */ - public static fromScaling(out:mat3, v:vec2):mat3 + public static fromScaling(out: mat3, v: vec2): mat3 /** * Copies the values from a mat2d into a mat3 @@ -2043,7 +2033,7 @@ export class mat3 extends Float32Array { * @param {mat2d} a the matrix to copy * @returns out **/ - public static fromMat2d(out:mat3, a:mat2d):mat3; + public static fromMat2d(out: mat3, a: mat2d): mat3; /** * Calculates a 3x3 matrix from the given quaternion @@ -2053,7 +2043,7 @@ export class mat3 extends Float32Array { * * @returns out */ - public static fromQuat(out:mat3, q:quat):mat3; + public static fromQuat(out: mat3, q: quat): mat3; /** * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix @@ -2063,7 +2053,7 @@ export class mat3 extends Float32Array { * * @returns out */ - public static normalFromMat4(out:mat3, a:mat4):mat3; + public static normalFromMat4(out: mat3, a: mat4): mat3; /** * Returns a string representation of a mat3 @@ -2071,7 +2061,7 @@ export class mat3 extends Float32Array { * @param mat matrix to represent as a string * @returns string representation of the matrix */ - public static str(mat:mat3):string; + public static str(mat: mat3):string; /** * Returns Frobenius norm of a mat3 @@ -2079,7 +2069,7 @@ export class mat3 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a:mat3):number; + public static frob(a: mat3):number; /** * Adds two mat3's @@ -2089,7 +2079,7 @@ export class mat3 extends Float32Array { * @param {mat3} b the second operand * @returns {mat3} out */ - public static add(out:mat3, a:mat3, b:mat3):mat3 + public static add(out: mat3, a: mat3, b: mat3): mat3 /** * Subtracts matrix b from matrix a @@ -2099,7 +2089,7 @@ export class mat3 extends Float32Array { * @param {mat3} b the second operand * @returns {mat3} out */ - public static subtract(out:mat3, a:mat3, b:mat3):mat3 + public static subtract(out: mat3, a: mat3, b: mat3): mat3 /** * Subtracts matrix b from matrix a @@ -2109,7 +2099,7 @@ export class mat3 extends Float32Array { * @param {mat3} b the second operand * @returns {mat3} out */ - public static sub(out:mat3, a:mat3, b:mat3):mat3 + public static sub(out: mat3, a: mat3, b: mat3): mat3 /** * Multiply each element of the matrix by a scalar. @@ -2119,7 +2109,7 @@ export class mat3 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat3} out */ - public static multiplyScalar(out:mat3, a:mat3, b:number):mat3 + public static multiplyScalar(out: mat3, a: mat3, b:number): mat3 /** * Adds two mat3's after multiplying each element of the second operand by a scalar value. @@ -2130,7 +2120,7 @@ export class mat3 extends Float32Array { * @param {number} scale the amount to scale b's elements by before adding * @returns {mat3} out */ - public static multiplyScalarAndAdd(out:mat3, a:mat3, b:mat3, scale:number):mat3 + public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale:number): mat3 /** * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) @@ -2139,7 +2129,7 @@ export class mat3 extends Float32Array { * @param {mat3} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals(a:mat3, b:mat3):boolean; + public static exactEquals(a: mat3, b: mat3):boolean; /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -2148,7 +2138,7 @@ export class mat3 extends Float32Array { * @param {mat3} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals(a:mat3, b:mat3):boolean + public static equals(a: mat3, b: mat3):boolean } // mat4 @@ -2160,7 +2150,7 @@ export class mat4 extends Float32Array { * * @returns a new 4x4 matrix */ - public static create():mat4; + public static create(): mat4; /** * Creates a new mat4 initialized with values from an existing matrix @@ -2168,7 +2158,7 @@ export class mat4 extends Float32Array { * @param a matrix to clone * @returns a new 4x4 matrix */ - public static clone(a:mat4):mat4; + public static clone(a: mat4): mat4; /** * Copy the values from one mat4 to another @@ -2177,7 +2167,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns out */ - public static copy(out:mat4, a:mat4):mat4; + public static copy(out: mat4, a: mat4): mat4; /** @@ -2201,7 +2191,7 @@ export class mat4 extends Float32Array { * @param {number} m33 Component in column 3, row 3 position (index 15) * @returns {mat4} A new mat4 */ - public static fromValues(m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number):mat4; + public static fromValues(m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number): mat4; /** * Set the components of a mat4 to the given values @@ -2225,7 +2215,7 @@ export class mat4 extends Float32Array { * @param {number} m33 Component in column 3, row 3 position (index 15) * @returns {mat4} out */ - public static set(out:mat4, m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number):mat4; + public static set(out: mat4, m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number): mat4; /** * Set a mat4 to the identity matrix @@ -2233,7 +2223,7 @@ export class mat4 extends Float32Array { * @param out the receiving matrix * @returns out */ - public static identity(out:mat4):mat4; + public static identity(out: mat4): mat4; /** * Transpose the values of a mat4 @@ -2242,7 +2232,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns out */ - public static transpose(out:mat4, a:mat4):mat4; + public static transpose(out: mat4, a: mat4): mat4; /** * Inverts a mat4 @@ -2251,7 +2241,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns out */ - public static invert(out:mat4, a:mat4):mat4; + public static invert(out: mat4, a: mat4): mat4; /** * Calculates the adjugate of a mat4 @@ -2260,7 +2250,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns out */ - public static adjoint(out:mat4, a:mat4):mat4; + public static adjoint(out: mat4, a: mat4): mat4; /** * Calculates the determinant of a mat4 @@ -2268,7 +2258,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a:mat4):number; + public static determinant(a: mat4):number; /** * Multiplies two mat4's @@ -2278,7 +2268,7 @@ export class mat4 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out:mat4, a:mat4, b:mat4):mat4; + public static multiply(out: mat4, a: mat4, b: mat4): mat4; /** * Multiplies two mat4's @@ -2288,7 +2278,7 @@ export class mat4 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out:mat4, a:mat4, b:mat4):mat4; + public static mul(out: mat4, a: mat4, b: mat4): mat4; /** * Translate a mat4 by the given vector @@ -2298,7 +2288,7 @@ export class mat4 extends Float32Array { * @param v vector to translate by * @returns out */ - public static translate(out:mat4, a:mat4, v:vec3):mat4; + public static translate(out: mat4, a: mat4, v: vec3): mat4; /** * Scales the mat4 by the dimensions in the given vec3 @@ -2308,7 +2298,7 @@ export class mat4 extends Float32Array { * @param v the vec3 to scale the matrix by * @returns out **/ - public static scale(out:mat4, a:mat4, v:vec3):mat4; + public static scale(out: mat4, a: mat4, v: vec3): mat4; /** * Rotates a mat4 by the given angle @@ -2319,7 +2309,7 @@ export class mat4 extends Float32Array { * @param axis the axis to rotate around * @returns out */ - public static rotate(out:mat4, a:mat4, rad:number, axis:vec3):mat4; + public static rotate(out: mat4, a: mat4, rad:number, axis: vec3): mat4; /** * Rotates a matrix by the given angle around the X axis @@ -2329,7 +2319,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateX(out:mat4, a:mat4, rad:number):mat4; + public static rotateX(out: mat4, a: mat4, rad:number): mat4; /** * Rotates a matrix by the given angle around the Y axis @@ -2339,7 +2329,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateY(out:mat4, a:mat4, rad:number):mat4; + public static rotateY(out: mat4, a: mat4, rad:number): mat4; /** * Rotates a matrix by the given angle around the Z axis @@ -2349,7 +2339,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateZ(out:mat4, a:mat4, rad:number):mat4; + public static rotateZ(out: mat4, a: mat4, rad:number): mat4; /** * Creates a matrix from a vector translation @@ -2362,7 +2352,7 @@ export class mat4 extends Float32Array { * @param {vec3} v Translation vector * @returns {mat4} out */ - public static fromTranslation(out:mat4, v:vec3):mat4 + public static fromTranslation(out: mat4, v: vec3): mat4 /** * Creates a matrix from a vector scaling @@ -2375,7 +2365,7 @@ export class mat4 extends Float32Array { * @param {vec3} v Scaling vector * @returns {mat4} out */ - public static fromScaling(out:mat4, v:vec3):mat4 + public static fromScaling(out: mat4, v: vec3): mat4 /** * Creates a matrix from a given angle around a given axis @@ -2389,7 +2379,7 @@ export class mat4 extends Float32Array { * @param {vec3} axis the axis to rotate around * @returns {mat4} out */ - public static fromRotation(out:mat4, rad:number, axis:vec3):mat4 + public static fromRotation(out: mat4, rad:number, axis: vec3): mat4 /** * Creates a matrix from the given angle around the X axis @@ -2402,7 +2392,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromXRotation(out:mat4, rad:number):mat4 + public static fromXRotation(out: mat4, rad:number): mat4 /** * Creates a matrix from the given angle around the Y axis @@ -2415,7 +2405,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromYRotation(out:mat4, rad:number):mat4 + public static fromYRotation(out: mat4, rad:number): mat4 /** @@ -2429,7 +2419,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromZRotation(out:mat4, rad:number):mat4 + public static fromZRotation(out: mat4, rad:number): mat4 /** * Creates a matrix from a quaternion rotation and vector translation @@ -2446,7 +2436,7 @@ export class mat4 extends Float32Array { * @param v Translation vector * @returns out */ - public static fromRotationTranslation(out:mat4, q:quat, v:vec3):mat4; + public static fromRotationTranslation(out: mat4, q: quat, v: vec3): mat4; /** * Returns the translation vector component of a transformation @@ -2457,7 +2447,7 @@ export class mat4 extends Float32Array { * @param {mat4} mat Matrix to be decomposed (input) * @return {vec3} out */ - public static getTranslation(out:vec3, mat:mat4):vec3; + public static getTranslation(out: vec3, mat: mat4): vec3; /** * Returns a quaternion representing the rotational component @@ -2468,7 +2458,7 @@ export class mat4 extends Float32Array { * @param {mat4} mat Matrix to be decomposed (input) * @return {quat} out */ - public static getRotation(out:quat, mat:mat4):quat; + public static getRotation(out: quat, mat: mat4): quat; /** * Creates a matrix from a quaternion rotation, vector translation and vector scale @@ -2487,7 +2477,7 @@ export class mat4 extends Float32Array { * @param s Scaling vector * @returns out */ - public static fromRotationTranslationScale(out:mat4, q:quat, v:vec3, s:vec3):mat4; + public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3, s: vec3): mat4; /** * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin @@ -2509,7 +2499,7 @@ export class mat4 extends Float32Array { * @param {vec3} o The origin vector around which to scale and rotate * @returns {mat4} out */ - public static fromRotationTranslationScaleOrigin(out:mat4, q:quat, v:vec3, s:vec3, o:vec3):mat4 + public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3, s: vec3, o: vec3): mat4 /** * Calculates a 4x4 matrix from the given quaternion @@ -2519,7 +2509,7 @@ export class mat4 extends Float32Array { * * @returns {mat4} out */ - public static fromQuat(out:mat4, q:quat):mat4 + public static fromQuat(out: mat4, q: quat): mat4 /** * Generates a frustum matrix with the given bounds @@ -2533,8 +2523,8 @@ export class mat4 extends Float32Array { * @param far Far bound of the frustum * @returns out */ - public static frustum(out:mat4, left:number, right:number, - bottom:number, top:number, near:number, far:number):mat4; + public static frustum(out: mat4, left:number, right:number, + bottom:number, top:number, near:number, far:number): mat4; /** * Generates a perspective projection matrix with the given bounds @@ -2546,8 +2536,8 @@ export class mat4 extends Float32Array { * @param far Far bound of the frustum * @returns out */ - public static perspective(out:mat4, fovy:number, aspect:number, - near:number, far:number):mat4; + public static perspective(out: mat4, fovy:number, aspect:number, + near:number, far:number): mat4; /** * Generates a perspective projection matrix with the given field of view. @@ -2560,9 +2550,9 @@ export class mat4 extends Float32Array { * @param {number} far Far bound of the frustum * @returns {mat4} out */ - public static perspectiveFromFieldOfView(out:mat4, + public static perspectiveFromFieldOfView(out: mat4, fov:{upDegrees:number, downDegrees:number, leftDegrees:number, rightDegrees:number}, - near:number, far:number):mat4 + near:number, far:number): mat4 /** * Generates a orthogonal projection matrix with the given bounds @@ -2576,8 +2566,8 @@ export class mat4 extends Float32Array { * @param far Far bound of the frustum * @returns out */ - public static ortho(out:mat4, left:number, right:number, - bottom:number, top:number, near:number, far:number):mat4; + public static ortho(out: mat4, left:number, right:number, + bottom:number, top:number, near:number, far:number): mat4; /** * Generates a look-at matrix with the given eye position, focal point, and up axis @@ -2588,7 +2578,7 @@ export class mat4 extends Float32Array { * @param up vec3 pointing up * @returns out */ - public static lookAt(out:mat4, eye:vec3, center:vec3, up:vec3):mat4; + public static lookAt(out: mat4, eye: vec3, center: vec3, up: vec3): mat4; /** * Returns a string representation of a mat4 @@ -2596,7 +2586,7 @@ export class mat4 extends Float32Array { * @param mat matrix to represent as a string * @returns string representation of the matrix */ - public static str(mat:mat4):string; + public static str(mat: mat4):string; /** * Returns Frobenius norm of a mat4 @@ -2604,7 +2594,7 @@ export class mat4 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a:mat4):number; + public static frob(a: mat4):number; /** * Adds two mat4's @@ -2614,7 +2604,7 @@ export class mat4 extends Float32Array { * @param {mat4} b the second operand * @returns {mat4} out */ - public static add(out:mat4, a:mat4, b:mat4):mat4 + public static add(out: mat4, a: mat4, b: mat4): mat4 /** * Subtracts matrix b from matrix a @@ -2624,7 +2614,7 @@ export class mat4 extends Float32Array { * @param {mat4} b the second operand * @returns {mat4} out */ - public static subtract(out:mat4, a:mat4, b:mat4):mat4 + public static subtract(out: mat4, a: mat4, b: mat4): mat4 /** * Subtracts matrix b from matrix a @@ -2634,7 +2624,7 @@ export class mat4 extends Float32Array { * @param {mat4} b the second operand * @returns {mat4} out */ - public static sub(out:mat4, a:mat4, b:mat4):mat4 + public static sub(out: mat4, a: mat4, b: mat4): mat4 /** * Multiply each element of the matrix by a scalar. @@ -2644,7 +2634,7 @@ export class mat4 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat4} out */ - public static multiplyScalar(out:mat4, a:mat4, b:number):mat4 + public static multiplyScalar(out: mat4, a: mat4, b:number): mat4 /** * Adds two mat4's after multiplying each element of the second operand by a scalar value. @@ -2655,7 +2645,7 @@ export class mat4 extends Float32Array { * @param {number} scale the amount to scale b's elements by before adding * @returns {mat4} out */ - public static multiplyScalarAndAdd (out:mat4, a:mat4, b:mat4, scale:number):mat4 + public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale:number): mat4 /** * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) @@ -2664,7 +2654,7 @@ export class mat4 extends Float32Array { * @param {mat4} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals (a:mat4, b:mat4) :boolean + public static exactEquals (a: mat4, b: mat4) :boolean /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -2673,7 +2663,7 @@ export class mat4 extends Float32Array { * @param {mat4} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals (a:mat4, b:mat4): boolean + public static equals (a: mat4, b: mat4): boolean } @@ -2740,6 +2730,18 @@ export class quat extends Float32Array { */ public static identity(out: quat): quat; + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} view the vector representing the viewing direction + * @param {vec3} right the vector representing the local "right" direction + * @param {vec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + public static setAxes (out: quat, view: vec3, right: vec3, up: vec3): quat + /** * Sets a quaternion to represent the shortest rotation from one * vector to another. @@ -2751,19 +2753,7 @@ export class quat extends Float32Array { * @param {vec3} b the destination vector * @returns {quat} out */ - public static rotationTo (out:quat, a:vec3, b:vec3): quat; - - /** - * Sets the specified quaternion with values corresponding to the given - * axes. Each axis is a vec3 and is expected to be unit length and - * perpendicular to all other specified axes. - * - * @param {vec3} view the vector representing the viewing direction - * @param {vec3} right the vector representing the local "right" direction - * @param {vec3} up the vector representing the local "up" direction - * @returns {quat} out - */ - public static setAxes (out:quat, view:vec3, right:vec3, up:vec3):quat + public static rotationTo (out: quat, a: vec3, b: vec3): quat; @@ -2791,7 +2781,7 @@ export class quat extends Float32Array { * @param {quat} q Quaternion to be decomposed * @return {number} Angle, in radians, of the rotation */ - public static getAxisAngle (out_axis:vec3, q:quat) :number + public static getAxisAngle (out_axis: vec3, q: quat) :number /** * Adds two quat's @@ -2912,7 +2902,7 @@ export class quat extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static slerp(out:quat, a:quat, b:quat, t:number): quat; + public static slerp(out: quat, a: quat, b: quat, t:number): quat; /** * Performs a spherical linear interpolation with two control points @@ -3041,7 +3031,7 @@ export class quat extends Float32Array { * @param {quat} b The second vector. * @returns {boolean} True if the quaternions are equal, false otherwise. */ - public static exactEquals (a:quat, b:quat) : boolean; + public static exactEquals (a: quat, b: quat) : boolean; /** * Returns whether or not the quaternions have approximately the same elements in the same position. @@ -3050,5 +3040,5 @@ export class quat extends Float32Array { * @param {quat} b The second vector. * @returns {boolean} True if the quaternions are equal, false otherwise. */ - public static equals (a:quat, b:quat) : boolean; + public static equals (a: quat, b: quat) : boolean; } From 568c64aa047cf20d2ff4a7e2128ccfa7bf326483 Mon Sep 17 00:00:00 2001 From: Mattijs Kneppers Date: Mon, 15 Aug 2016 17:47:26 +0200 Subject: [PATCH 035/844] feature: add option of number array input for all vector arguments --- gl-matrix/gl-matrix-typed-tests.ts | 4 +- gl-matrix/gl-matrix-typed.d.ts | 430 ++++++++++++++--------------- 2 files changed, 218 insertions(+), 216 deletions(-) diff --git a/gl-matrix/gl-matrix-typed-tests.ts b/gl-matrix/gl-matrix-typed-tests.ts index 361690b5e7..64f6beb7a4 100644 --- a/gl-matrix/gl-matrix-typed-tests.ts +++ b/gl-matrix/gl-matrix-typed-tests.ts @@ -79,6 +79,7 @@ vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); outStr = vec2.str(vec2A); outBool = vec2.exactEquals(vec2A, vec2B); outBool = vec2.equals(vec2A, vec2B); +outVec2 = vec2.add(outVec2, [0, 1], [2, 3]); // test one method with number array input // vec3 outVec3 = vec3.create(); @@ -129,6 +130,7 @@ outVal = vec3.angle(vec3A, vec3B); outStr = vec3.str(vec3A); outBool = vec3.exactEquals(vec3A, vec3B); outBool = vec3.equals(vec3A, vec3B); +outVec3 = vec3.add(outVec3, [0, 1, 2], [3, 4, 5]); // test one method with number array input // vec4 outVec4 = vec4.create(); @@ -170,6 +172,7 @@ vecArray = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); outStr = vec4.str(vec4A); outBool = vec4.exactEquals(vec4A, vec4B); outBool = vec4.equals(vec4A, vec4B); +outVec4 = vec4.add(outVec4, [0, 1, 2, 3], [4, 5, 6, 7]); // test one method with number array input // mat2 outMat2 = mat2.create(); @@ -229,7 +232,6 @@ outMat2d = mat2d.multiplyScalarAndAdd (outMat2d, mat2dA, mat2dB, 2); outBool = mat2d.exactEquals(mat2dA, mat2dB); outBool = mat2d.equals(mat2dA, mat2dB); - // mat3 outMat3 = mat3.create(); outMat3 = mat3.fromMat4(outMat3, mat4A); diff --git a/gl-matrix/gl-matrix-typed.d.ts b/gl-matrix/gl-matrix-typed.d.ts index 1309e994c8..2edbbd8bb5 100644 --- a/gl-matrix/gl-matrix-typed.d.ts +++ b/gl-matrix/gl-matrix-typed.d.ts @@ -5,7 +5,7 @@ // vec2 export class vec2 extends Float32Array { - private typeVec2:number; + private typeVec2: number; /** * Creates a new, empty vec2 @@ -20,7 +20,7 @@ export class vec2 extends Float32Array { * @param a a vector to clone * @returns a new 2D vector */ - public static clone(a: vec2): vec2; + public static clone(a: vec2 | number[]): vec2; /** * Creates a new vec2 initialized with the given values @@ -38,7 +38,7 @@ export class vec2 extends Float32Array { * @param a the source vector * @returns out */ - public static copy(out: vec2, a: vec2): vec2; + public static copy(out: vec2, a: vec2 | number[]): vec2; /** * Set the components of a vec2 to the given values @@ -58,7 +58,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static add(out: vec2, a: vec2, b: vec2): vec2; + public static add(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Subtracts vector b from vector a @@ -68,7 +68,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static subtract(out: vec2, a: vec2, b: vec2): vec2; + public static subtract(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Subtracts vector b from vector a @@ -78,7 +78,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static sub(out: vec2, a: vec2, b: vec2): vec2; + public static sub(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Multiplies two vec2's @@ -88,7 +88,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out: vec2, a: vec2, b: vec2): vec2; + public static multiply(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Multiplies two vec2's @@ -98,7 +98,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out: vec2, a: vec2, b: vec2): vec2; + public static mul(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Divides two vec2's @@ -108,7 +108,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static divide(out: vec2, a: vec2, b: vec2): vec2; + public static divide(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Divides two vec2's @@ -118,7 +118,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static div(out: vec2, a: vec2, b: vec2): vec2; + public static div(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Math.ceil the components of a vec2 @@ -127,7 +127,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to ceil * @returns {vec2} out */ - public static ceil(out: vec2, a: vec2): vec2; + public static ceil(out: vec2, a: vec2 | number[]): vec2; /** * Math.floor the components of a vec2 @@ -136,7 +136,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to floor * @returns {vec2} out */ - public static floor (out: vec2, a: vec2): vec2; + public static floor (out: vec2, a: vec2 | number[]): vec2; /** * Returns the minimum of two vec2's @@ -146,7 +146,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static min(out: vec2, a: vec2, b: vec2): vec2; + public static min(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Returns the maximum of two vec2's @@ -156,7 +156,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static max(out: vec2, a: vec2, b: vec2): vec2; + public static max(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Math.round the components of a vec2 @@ -165,7 +165,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to round * @returns {vec2} out */ - public static round(out: vec2, a: vec2): vec2; + public static round(out: vec2, a: vec2 | number[]): vec2; /** @@ -176,7 +176,7 @@ export class vec2 extends Float32Array { * @param b amount to scale the vector by * @returns out */ - public static scale(out: vec2, a: vec2, b: number): vec2; + public static scale(out: vec2, a: vec2 | number[], b: number): vec2; /** * Adds two vec2's after scaling the second operand by a scalar value @@ -187,7 +187,7 @@ export class vec2 extends Float32Array { * @param scale the amount to scale b by before adding * @returns out */ - public static scaleAndAdd(out: vec2, a: vec2, b: vec2, scale: number): vec2; + public static scaleAndAdd(out: vec2, a: vec2 | number[], b: vec2 | number[], scale: number): vec2; /** * Calculates the euclidian distance between two vec2's @@ -196,7 +196,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static distance(a: vec2, b: vec2): number; + public static distance(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the euclidian distance between two vec2's @@ -205,7 +205,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static dist(a: vec2, b: vec2): number; + public static dist(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the squared euclidian distance between two vec2's @@ -214,7 +214,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static squaredDistance(a: vec2, b: vec2): number; + public static squaredDistance(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the squared euclidian distance between two vec2's @@ -223,7 +223,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static sqrDist(a: vec2, b: vec2): number; + public static sqrDist(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the length of a vec2 @@ -231,7 +231,7 @@ export class vec2 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static length(a: vec2): number; + public static length(a: vec2 | number[]): number; /** * Calculates the length of a vec2 @@ -239,7 +239,7 @@ export class vec2 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static len(a: vec2): number; + public static len(a: vec2 | number[]): number; /** * Calculates the squared length of a vec2 @@ -247,7 +247,7 @@ export class vec2 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static squaredLength(a: vec2): number; + public static squaredLength(a: vec2 | number[]): number; /** * Calculates the squared length of a vec2 @@ -255,7 +255,7 @@ export class vec2 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static sqrLen(a: vec2): number; + public static sqrLen(a: vec2 | number[]): number; /** * Negates the components of a vec2 @@ -264,7 +264,7 @@ export class vec2 extends Float32Array { * @param a vector to negate * @returns out */ - public static negate(out: vec2, a: vec2): vec2; + public static negate(out: vec2, a: vec2 | number[]): vec2; /** * Returns the inverse of the components of a vec2 @@ -273,7 +273,7 @@ export class vec2 extends Float32Array { * @param a vector to invert * @returns out */ - public static inverse(out: vec2, a: vec2): vec2; + public static inverse(out: vec2, a: vec2 | number[]): vec2; /** * Normalize a vec2 @@ -282,7 +282,7 @@ export class vec2 extends Float32Array { * @param a vector to normalize * @returns out */ - public static normalize(out: vec2, a: vec2): vec2; + public static normalize(out: vec2, a: vec2 | number[]): vec2; /** * Calculates the dot product of two vec2's @@ -291,7 +291,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns dot product of a and b */ - public static dot(a: vec2, b: vec2): number; + public static dot(a: vec2 | number[], b: vec2 | number[]): number; /** * Computes the cross product of two vec2's @@ -302,7 +302,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static cross(out: vec2, a: vec2, b: vec2): vec2; + public static cross(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Performs a linear interpolation between two vec2's @@ -313,7 +313,7 @@ export class vec2 extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static lerp(out: vec2, a: vec2, b: vec2, t: number): vec2; + public static lerp(out: vec2, a: vec2 | number[], b: vec2 | number[], t: number): vec2; /** * Generates a random unit vector @@ -340,7 +340,7 @@ export class vec2 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat2(out: vec2, a: vec2, m: mat2): vec2; + public static transformMat2(out: vec2, a: vec2 | number[], m: mat2): vec2; /** * Transforms the vec2 with a mat2d @@ -350,7 +350,7 @@ export class vec2 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat2d(out: vec2, a: vec2, m: mat2d): vec2; + public static transformMat2d(out: vec2, a: vec2 | number[], m: mat2d): vec2; /** * Transforms the vec2 with a mat3 @@ -361,7 +361,7 @@ export class vec2 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat3(out: vec2, a: vec2, m: mat3): vec2; + public static transformMat3(out: vec2, a: vec2 | number[], m: mat3): vec2; /** * Transforms the vec2 with a mat4 @@ -373,7 +373,7 @@ export class vec2 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat4(out: vec2, a: vec2, m: mat4): vec2; + public static transformMat4(out: vec2, a: vec2 | number[], m: mat4): vec2; /** * Perform some operation over an array of vec2s. @@ -387,7 +387,7 @@ export class vec2 extends Float32Array { * @returns a */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2, b: vec2, arg: any) => void, arg: any): Float32Array; + fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec2s. @@ -400,7 +400,7 @@ export class vec2 extends Float32Array { * @returns a */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2, b: vec2) => void): Float32Array; + fn: (a: vec2 | number[], b: vec2 | number[]) => void): Float32Array; /** * Returns a string representation of a vector @@ -408,7 +408,7 @@ export class vec2 extends Float32Array { * @param a vector to represent as a string * @returns string representation of the vector */ - public static str(a: vec2): string; + public static str(a: vec2 | number[]): string; /** * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) @@ -417,7 +417,7 @@ export class vec2 extends Float32Array { * @param {vec2} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a: vec2, b: vec2): boolean; + public static exactEquals (a: vec2 | number[], b: vec2 | number[]): boolean; /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -426,12 +426,12 @@ export class vec2 extends Float32Array { * @param {vec2} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a: vec2, b: vec2) : boolean; + public static equals (a: vec2 | number[], b: vec2 | number[]): boolean; } // vec3 export class vec3 extends Float32Array { - private typeVec3:number; + private typeVec3: number; /** * Creates a new, empty vec3 @@ -446,7 +446,7 @@ export class vec3 extends Float32Array { * @param a vector to clone * @returns a new 3D vector */ - public static clone(a: vec3): vec3; + public static clone(a: vec3 | number[]): vec3; /** * Creates a new vec3 initialized with the given values @@ -465,7 +465,7 @@ export class vec3 extends Float32Array { * @param a the source vector * @returns out */ - public static copy(out: vec3, a: vec3): vec3; + public static copy(out: vec3, a: vec3 | number[]): vec3; /** * Set the components of a vec3 to the given values @@ -486,7 +486,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static add(out: vec3, a: vec3, b: vec3): vec3; + public static add(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Subtracts vector b from vector a @@ -496,7 +496,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static subtract(out: vec3, a: vec3, b: vec3): vec3; + public static subtract(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Subtracts vector b from vector a @@ -506,7 +506,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static sub(out: vec3, a: vec3, b: vec3): vec3 + public static sub(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3 /** * Multiplies two vec3's @@ -516,7 +516,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out: vec3, a: vec3, b: vec3): vec3; + public static multiply(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Multiplies two vec3's @@ -526,7 +526,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out: vec3, a: vec3, b: vec3): vec3; + public static mul(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Divides two vec3's @@ -536,7 +536,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static divide(out: vec3, a: vec3, b: vec3): vec3; + public static divide(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Divides two vec3's @@ -546,7 +546,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static div(out: vec3, a: vec3, b: vec3): vec3; + public static div(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Math.ceil the components of a vec3 @@ -555,7 +555,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to ceil * @returns {vec3} out */ - public static ceil (out: vec3, a: vec3) : vec3; + public static ceil (out: vec3, a: vec3 | number[]): vec3; /** * Math.floor the components of a vec3 @@ -564,7 +564,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to floor * @returns {vec3} out */ - public static floor (out: vec3, a: vec3) : vec3; + public static floor (out: vec3, a: vec3 | number[]): vec3; /** * Returns the minimum of two vec3's @@ -574,7 +574,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static min(out: vec3, a: vec3, b: vec3): vec3; + public static min(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Returns the maximum of two vec3's @@ -584,7 +584,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static max(out: vec3, a: vec3, b: vec3): vec3; + public static max(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Math.round the components of a vec3 @@ -593,7 +593,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to round * @returns {vec3} out */ - public static round (out: vec3, a: vec3) : vec3 + public static round (out: vec3, a: vec3 | number[]): vec3 /** * Scales a vec3 by a scalar number @@ -603,7 +603,7 @@ export class vec3 extends Float32Array { * @param b amount to scale the vector by * @returns out */ - public static scale(out: vec3, a: vec3, b: number): vec3; + public static scale(out: vec3, a: vec3 | number[], b: number): vec3; /** * Adds two vec3's after scaling the second operand by a scalar value @@ -614,7 +614,7 @@ export class vec3 extends Float32Array { * @param scale the amount to scale b by before adding * @returns out */ - public static scaleAndAdd(out: vec3, a: vec3, b: vec3, scale: number): vec3; + public static scaleAndAdd(out: vec3, a: vec3 | number[], b: vec3 | number[], scale: number): vec3; /** * Calculates the euclidian distance between two vec3's @@ -623,7 +623,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static distance(a: vec3, b: vec3): number; + public static distance(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the euclidian distance between two vec3's @@ -632,7 +632,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static dist(a: vec3, b: vec3): number; + public static dist(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the squared euclidian distance between two vec3's @@ -641,7 +641,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static squaredDistance(a: vec3, b: vec3): number; + public static squaredDistance(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the squared euclidian distance between two vec3's @@ -650,7 +650,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static sqrDist(a: vec3, b: vec3): number; + public static sqrDist(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the length of a vec3 @@ -658,7 +658,7 @@ export class vec3 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static length(a: vec3): number; + public static length(a: vec3 | number[]): number; /** * Calculates the length of a vec3 @@ -666,7 +666,7 @@ export class vec3 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static len(a: vec3): number; + public static len(a: vec3 | number[]): number; /** * Calculates the squared length of a vec3 @@ -674,7 +674,7 @@ export class vec3 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static squaredLength(a: vec3): number; + public static squaredLength(a: vec3 | number[]): number; /** * Calculates the squared length of a vec3 @@ -682,7 +682,7 @@ export class vec3 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static sqrLen(a: vec3): number; + public static sqrLen(a: vec3 | number[]): number; /** * Negates the components of a vec3 @@ -691,7 +691,7 @@ export class vec3 extends Float32Array { * @param a vector to negate * @returns out */ - public static negate(out: vec3, a: vec3): vec3; + public static negate(out: vec3, a: vec3 | number[]): vec3; /** * Returns the inverse of the components of a vec3 @@ -700,7 +700,7 @@ export class vec3 extends Float32Array { * @param a vector to invert * @returns out */ - public static inverse(out: vec3, a: vec3): vec3; + public static inverse(out: vec3, a: vec3 | number[]): vec3; /** * Normalize a vec3 @@ -709,7 +709,7 @@ export class vec3 extends Float32Array { * @param a vector to normalize * @returns out */ - public static normalize(out: vec3, a: vec3): vec3; + public static normalize(out: vec3, a: vec3 | number[]): vec3; /** * Calculates the dot product of two vec3's @@ -718,7 +718,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns dot product of a and b */ - public static dot(a: vec3, b: vec3): number; + public static dot(a: vec3 | number[], b: vec3 | number[]): number; /** * Computes the cross product of two vec3's @@ -728,7 +728,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static cross(out: vec3, a: vec3, b: vec3): vec3; + public static cross(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Performs a linear interpolation between two vec3's @@ -739,7 +739,7 @@ export class vec3 extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static lerp(out: vec3, a: vec3, b: vec3, t: number): vec3; + public static lerp(out: vec3, a: vec3 | number[], b: vec3 | number[], t: number): vec3; /** * Performs a hermite interpolation with two control points @@ -752,7 +752,7 @@ export class vec3 extends Float32Array { * @param {number} t interpolation amount between the two inputs * @returns {vec3} out */ - public static hermite (out: vec3, a: vec3, b: vec3, c: vec3, d: vec3, t:number) : vec3; + public static hermite (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; /** * Performs a bezier interpolation with two control points @@ -765,7 +765,7 @@ export class vec3 extends Float32Array { * @param {number} t interpolation amount between the two inputs * @returns {vec3} out */ - public static bezier (out: vec3, a: vec3, b: vec3, c: vec3, d: vec3, t:number) : vec3; + public static bezier (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; /** * Generates a random unit vector @@ -792,7 +792,7 @@ export class vec3 extends Float32Array { * @param m the 3x3 matrix to transform with * @returns out */ - public static transformMat3(out: vec3, a: vec3, m: mat3): vec3; + public static transformMat3(out: vec3, a: vec3 | number[], m: mat3): vec3; /** * Transforms the vec3 with a mat4. @@ -803,7 +803,7 @@ export class vec3 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat4(out: vec3, a: vec3, m: mat4): vec3; + public static transformMat4(out: vec3, a: vec3 | number[], m: mat4): vec3; /** * Transforms the vec3 with a quat @@ -813,7 +813,7 @@ export class vec3 extends Float32Array { * @param q quaternion to transform with * @returns out */ - public static transformQuat(out: vec3, a: vec3, q: quat): vec3; + public static transformQuat(out: vec3, a: vec3 | number[], q: quat): vec3; /** @@ -824,7 +824,7 @@ export class vec3 extends Float32Array { * @param c The angle of rotation * @returns out */ - public static rotateX(out: vec3, a: vec3, b: vec3, c: number): vec3; + public static rotateX(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; /** * Rotate a 3D vector around the y-axis @@ -834,7 +834,7 @@ export class vec3 extends Float32Array { * @param c The angle of rotation * @returns out */ - public static rotateY(out: vec3, a: vec3, b: vec3, c: number): vec3; + public static rotateY(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; /** * Rotate a 3D vector around the z-axis @@ -844,7 +844,7 @@ export class vec3 extends Float32Array { * @param c The angle of rotation * @returns out */ - public static rotateZ(out: vec3, a: vec3, b: vec3, c: number): vec3; + public static rotateZ(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; /** * Perform some operation over an array of vec3s. @@ -859,7 +859,7 @@ export class vec3 extends Float32Array { * @function */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3, b: vec3, arg: any) => void, arg: any): Float32Array; + fn: (a: vec3 | number[], b: vec3 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec3s. @@ -873,7 +873,7 @@ export class vec3 extends Float32Array { * @function */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3, b: vec3) => void): Float32Array; + fn: (a: vec3 | number[], b: vec3 | number[]) => void): Float32Array; /** * Get the angle between two 3D vectors @@ -881,7 +881,7 @@ export class vec3 extends Float32Array { * @param b The second operand * @returns The angle in radians */ - public static angle(a: vec3, b: vec3): number; + public static angle(a: vec3 | number[], b: vec3 | number[]): number; /** * Returns a string representation of a vector @@ -889,7 +889,7 @@ export class vec3 extends Float32Array { * @param a vector to represent as a string * @returns string representation of the vector */ - public static str(a: vec3): string; + public static str(a: vec3 | number[]): string; /** * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) @@ -898,7 +898,7 @@ export class vec3 extends Float32Array { * @param {vec3} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a: vec3, b: vec3): boolean + public static exactEquals (a: vec3 | number[], b: vec3 | number[]): boolean /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -907,12 +907,12 @@ export class vec3 extends Float32Array { * @param {vec3} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a: vec3, b: vec3) : boolean + public static equals (a: vec3 | number[], b: vec3 | number[]): boolean } // vec4 export class vec4 extends Float32Array { - private typeVec3:number; + private typeVec3: number; /** * Creates a new, empty vec4 @@ -927,7 +927,7 @@ export class vec4 extends Float32Array { * @param a vector to clone * @returns a new 4D vector */ - public static clone(a: vec4): vec4; + public static clone(a: vec4 | number[]): vec4; /** * Creates a new vec4 initialized with the given values @@ -947,7 +947,7 @@ export class vec4 extends Float32Array { * @param a the source vector * @returns out */ - public static copy(out: vec4, a: vec4): vec4; + public static copy(out: vec4, a: vec4 | number[]): vec4; /** * Set the components of a vec4 to the given values @@ -969,7 +969,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static add(out: vec4, a: vec4, b: vec4): vec4; + public static add(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Subtracts vector b from vector a @@ -979,7 +979,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static subtract(out: vec4, a: vec4, b: vec4): vec4; + public static subtract(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Subtracts vector b from vector a @@ -989,7 +989,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static sub(out: vec4, a: vec4, b: vec4): vec4; + public static sub(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Multiplies two vec4's @@ -999,7 +999,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out: vec4, a: vec4, b: vec4): vec4; + public static multiply(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Multiplies two vec4's @@ -1009,7 +1009,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out: vec4, a: vec4, b: vec4): vec4; + public static mul(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Divides two vec4's @@ -1019,7 +1019,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static divide(out: vec4, a: vec4, b: vec4): vec4; + public static divide(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Divides two vec4's @@ -1029,7 +1029,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static div(out: vec4, a: vec4, b: vec4): vec4; + public static div(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Math.ceil the components of a vec4 @@ -1038,7 +1038,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to ceil * @returns {vec4} out */ - public static ceil (out: vec4, a: vec4) : vec4; + public static ceil (out: vec4, a: vec4 | number[]): vec4; /** * Math.floor the components of a vec4 @@ -1047,7 +1047,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to floor * @returns {vec4} out */ - public static floor (out: vec4, a: vec4) : vec4; + public static floor (out: vec4, a: vec4 | number[]): vec4; /** * Returns the minimum of two vec4's @@ -1057,7 +1057,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static min(out: vec4, a: vec4, b: vec4): vec4; + public static min(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Returns the maximum of two vec4's @@ -1067,7 +1067,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static max(out: vec4, a: vec4, b: vec4): vec4; + public static max(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Math.round the components of a vec4 @@ -1076,7 +1076,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to round * @returns {vec4} out */ - public static round (out: vec4, a: vec4): vec4; + public static round (out: vec4, a: vec4 | number[]): vec4; /** * Scales a vec4 by a scalar number @@ -1086,7 +1086,7 @@ export class vec4 extends Float32Array { * @param b amount to scale the vector by * @returns out */ - public static scale(out: vec4, a: vec4, b: number): vec4; + public static scale(out: vec4, a: vec4 | number[], b: number): vec4; /** * Adds two vec4's after scaling the second operand by a scalar value @@ -1097,7 +1097,7 @@ export class vec4 extends Float32Array { * @param scale the amount to scale b by before adding * @returns out */ - public static scaleAndAdd(out: vec4, a: vec4, b: vec4, scale: number): vec4; + public static scaleAndAdd(out: vec4, a: vec4 | number[], b: vec4 | number[], scale: number): vec4; /** * Calculates the euclidian distance between two vec4's @@ -1106,7 +1106,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static distance(a: vec4, b: vec4): number; + public static distance(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the euclidian distance between two vec4's @@ -1115,7 +1115,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static dist(a: vec4, b: vec4): number; + public static dist(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the squared euclidian distance between two vec4's @@ -1124,7 +1124,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static squaredDistance(a: vec4, b: vec4): number; + public static squaredDistance(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the squared euclidian distance between two vec4's @@ -1133,7 +1133,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static sqrDist(a: vec4, b: vec4): number; + public static sqrDist(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the length of a vec4 @@ -1141,7 +1141,7 @@ export class vec4 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static length(a: vec4): number; + public static length(a: vec4 | number[]): number; /** * Calculates the length of a vec4 @@ -1149,7 +1149,7 @@ export class vec4 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static len(a: vec4): number; + public static len(a: vec4 | number[]): number; /** * Calculates the squared length of a vec4 @@ -1157,7 +1157,7 @@ export class vec4 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static squaredLength(a: vec4): number; + public static squaredLength(a: vec4 | number[]): number; /** * Calculates the squared length of a vec4 @@ -1165,7 +1165,7 @@ export class vec4 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static sqrLen(a: vec4): number; + public static sqrLen(a: vec4 | number[]): number; /** * Negates the components of a vec4 @@ -1174,7 +1174,7 @@ export class vec4 extends Float32Array { * @param a vector to negate * @returns out */ - public static negate(out: vec4, a: vec4): vec4; + public static negate(out: vec4, a: vec4 | number[]): vec4; /** * Returns the inverse of the components of a vec4 @@ -1183,7 +1183,7 @@ export class vec4 extends Float32Array { * @param a vector to invert * @returns out */ - public static inverse(out: vec4, a: vec4): vec4; + public static inverse(out: vec4, a: vec4 | number[]): vec4; /** * Normalize a vec4 @@ -1192,7 +1192,7 @@ export class vec4 extends Float32Array { * @param a vector to normalize * @returns out */ - public static normalize(out: vec4, a: vec4): vec4; + public static normalize(out: vec4, a: vec4 | number[]): vec4; /** * Calculates the dot product of two vec4's @@ -1201,7 +1201,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns dot product of a and b */ - public static dot(a: vec4, b: vec4): number; + public static dot(a: vec4 | number[], b: vec4 | number[]): number; /** * Performs a linear interpolation between two vec4's @@ -1212,7 +1212,7 @@ export class vec4 extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static lerp(out: vec4, a: vec4, b: vec4, t: number): vec4; + public static lerp(out: vec4, a: vec4 | number[], b: vec4 | number[], t: number): vec4; /** * Generates a random unit vector @@ -1239,7 +1239,7 @@ export class vec4 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat4(out: vec4, a: vec4, m: mat4): vec4; + public static transformMat4(out: vec4, a: vec4 | number[], m: mat4): vec4; /** * Transforms the vec4 with a quat @@ -1250,7 +1250,7 @@ export class vec4 extends Float32Array { * @returns out */ - public static transformQuat(out: vec4, a: vec4, q: quat): vec4; + public static transformQuat(out: vec4, a: vec4 | number[], q: quat): vec4; /** * Perform some operation over an array of vec4s. @@ -1265,7 +1265,7 @@ export class vec4 extends Float32Array { * @function */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4, b: vec4, arg: any) => void, arg: any): Float32Array; + fn: (a: vec4 | number[], b: vec4 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec4s. @@ -1279,7 +1279,7 @@ export class vec4 extends Float32Array { * @function */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4, b: vec4) => void): Float32Array; + fn: (a: vec4 | number[], b: vec4 | number[]) => void): Float32Array; /** * Returns a string representation of a vector @@ -1287,7 +1287,7 @@ export class vec4 extends Float32Array { * @param a vector to represent as a string * @returns string representation of the vector */ - public static str(a: vec4): string; + public static str(a: vec4 | number[]): string; /** * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) @@ -1296,7 +1296,7 @@ export class vec4 extends Float32Array { * @param {vec4} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a: vec4, b: vec4) : boolean; + public static exactEquals (a: vec4 | number[], b: vec4 | number[]): boolean; /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -1305,12 +1305,12 @@ export class vec4 extends Float32Array { * @param {vec4} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a: vec4, b: vec4) : boolean; + public static equals (a: vec4 | number[], b: vec4 | number[]): boolean; } // mat2 export class mat2 extends Float32Array { - private typeMat2:number; + private typeMat2: number; /** * Creates a new identity mat2 @@ -1353,7 +1353,7 @@ export class mat2 extends Float32Array { * @param {number} m11 Component in column 1, row 1 position (index 3) * @returns {mat2} out A new 2x2 matrix */ - public static fromValues(m00:number, m01:number, m10:number, m11:number): mat2; + public static fromValues(m00: number, m01: number, m10: number, m11: number): mat2; /** * Set the components of a mat2 to the given values @@ -1365,7 +1365,7 @@ export class mat2 extends Float32Array { * @param {number} m11 Component in column 1, row 1 position (index 3) * @returns {mat2} out */ - public static set(out: mat2, m00:number, m01:number, m10:number, m11:number): mat2; + public static set(out: mat2, m00: number, m01: number, m10: number, m11: number): mat2; /** * Transpose the values of a mat2 @@ -1400,7 +1400,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a: mat2):number; + public static determinant(a: mat2): number; /** * Multiplies two mat2's @@ -1430,7 +1430,7 @@ export class mat2 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotate(out: mat2, a: mat2, rad:number): mat2; + public static rotate(out: mat2, a: mat2, rad: number): mat2; /** * Scales the mat2 by the dimensions in the given vec2 @@ -1440,7 +1440,7 @@ export class mat2 extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out: mat2, a: mat2, v: vec2): mat2; + public static scale(out: mat2, a: mat2, v: vec2 | number[]): mat2; /** * Creates a matrix from a given angle @@ -1453,7 +1453,7 @@ export class mat2 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat2} out */ - public static fromRotation(out: mat2, rad:number): mat2; + public static fromRotation(out: mat2, rad: number): mat2; /** * Creates a matrix from a vector scaling @@ -1466,7 +1466,7 @@ export class mat2 extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat2} out */ - public static fromScaling(out: mat2, v: vec2): mat2; + public static fromScaling(out: mat2, v: vec2 | number[]): mat2; /** * Returns a string representation of a mat2 @@ -1474,7 +1474,7 @@ export class mat2 extends Float32Array { * @param a matrix to represent as a string * @returns string representation of the matrix */ - public static str(a: mat2):string; + public static str(a: mat2): string; /** * Returns Frobenius norm of a mat2 @@ -1482,7 +1482,7 @@ export class mat2 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a: mat2):number; + public static frob(a: mat2): number; /** * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix @@ -1530,7 +1530,7 @@ export class mat2 extends Float32Array { * @param {mat2} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals (a: mat2, b: mat2):boolean; + public static exactEquals (a: mat2, b: mat2): boolean; /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -1539,7 +1539,7 @@ export class mat2 extends Float32Array { * @param {mat2} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals (a: mat2, b: mat2) :boolean; + public static equals (a: mat2, b: mat2): boolean; /** * Multiply each element of the matrix by a scalar. @@ -1549,7 +1549,7 @@ export class mat2 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat2} out */ - public static multiplyScalar (out: mat2, a: mat2, b:number) : mat2 + public static multiplyScalar (out: mat2, a: mat2, b: number): mat2 /** * Adds two mat2's after multiplying each element of the second operand by a scalar value. @@ -1560,7 +1560,7 @@ export class mat2 extends Float32Array { * @param {number} scale the amount to scale b's elements by before adding * @returns {mat2} out */ - public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale:number): mat2 + public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale: number): mat2 @@ -1568,7 +1568,7 @@ export class mat2 extends Float32Array { // mat2d export class mat2d extends Float32Array { - private typeMat2d:number; + private typeMat2d: number; /** * Creates a new identity mat2d @@ -1613,7 +1613,7 @@ export class mat2d extends Float32Array { * @param {number} ty Component TY (index 5) * @returns {mat2d} A new mat2d */ - public static fromValues (a:number, b:number, c:number, d:number, tx:number, ty:number) : mat2d + public static fromValues (a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d /** @@ -1628,7 +1628,7 @@ export class mat2d extends Float32Array { * @param {number} ty Component TY (index 5) * @returns {mat2d} out */ - public static set (out: mat2d, a:number, b:number, c:number, d:number, tx:number, ty:number) : mat2d + public static set (out: mat2d, a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d /** * Inverts a mat2d @@ -1685,7 +1685,7 @@ export class mat2d extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out: mat2d, a: mat2d, v: vec2): mat2d; + public static scale(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; /** * Translates the mat2d by the dimensions in the given vec2 @@ -1695,7 +1695,7 @@ export class mat2d extends Float32Array { * @param v the vec2 to translate the matrix by * @returns out **/ - public static translate(out: mat2d, a: mat2d, v: vec2): mat2d; + public static translate(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; /** * Creates a matrix from a given angle @@ -1708,7 +1708,7 @@ export class mat2d extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat2d} out */ - public static fromRotation (out: mat2d, rad:number): mat2d; + public static fromRotation (out: mat2d, rad: number): mat2d; /** * Creates a matrix from a vector scaling @@ -1721,7 +1721,7 @@ export class mat2d extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat2d} out */ - public static fromScaling (out: mat2d, v: vec2): mat2d; + public static fromScaling (out: mat2d, v: vec2 | number[]): mat2d; /** * Creates a matrix from a vector translation @@ -1734,7 +1734,7 @@ export class mat2d extends Float32Array { * @param {vec2} v Translation vector * @returns {mat2d} out */ - public static fromTranslation (out: mat2d, v: vec2): mat2d + public static fromTranslation (out: mat2d, v: vec2 | number[]): mat2d /** * Returns a string representation of a mat2d @@ -1801,7 +1801,7 @@ export class mat2d extends Float32Array { * @param {number} scale the amount to scale b's elements by before adding * @returns {mat2d} out */ - public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale:number) : mat2d + public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale: number): mat2d /** * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) @@ -1824,7 +1824,7 @@ export class mat2d extends Float32Array { // mat3 export class mat3 extends Float32Array { - private typeMat3:number; + private typeMat3: number; /** * Creates a new identity mat3 @@ -1873,7 +1873,7 @@ export class mat3 extends Float32Array { * @param {number} m22 Component in column 2, row 2 position (index 8) * @returns {mat3} A new mat3 */ - public static fromValues(m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number): mat3; + public static fromValues(m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3; /** @@ -1891,7 +1891,7 @@ export class mat3 extends Float32Array { * @param {number} m22 Component in column 2, row 2 position (index 8) * @returns {mat3} out */ - public static set(out: mat3, m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number): mat3 + public static set(out: mat3, m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3 /** * Set a mat3 to the identity matrix @@ -1934,7 +1934,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a: mat3):number; + public static determinant(a: mat3): number; /** * Multiplies two mat3's @@ -1965,7 +1965,7 @@ export class mat3 extends Float32Array { * @param v vector to translate by * @returns out */ - public static translate(out: mat3, a: mat3, v: vec3): mat3; + public static translate(out: mat3, a: mat3, v: vec3 | number[]): mat3; /** * Rotates a mat3 by the given angle @@ -1975,7 +1975,7 @@ export class mat3 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotate(out: mat3, a: mat3, rad:number): mat3; + public static rotate(out: mat3, a: mat3, rad: number): mat3; /** * Scales the mat3 by the dimensions in the given vec2 @@ -1985,7 +1985,7 @@ export class mat3 extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out: mat3, a: mat3, v: vec2): mat3; + public static scale(out: mat3, a: mat3, v: vec2 | number[]): mat3; /** * Creates a matrix from a vector translation @@ -1998,7 +1998,7 @@ export class mat3 extends Float32Array { * @param {vec2} v Translation vector * @returns {mat3} out */ - public static fromTranslation(out: mat3, v: vec2): mat3 + public static fromTranslation(out: mat3, v: vec2 | number[]): mat3 /** * Creates a matrix from a given angle @@ -2011,7 +2011,7 @@ export class mat3 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat3} out */ - public static fromRotation(out: mat3, rad:number): mat3 + public static fromRotation(out: mat3, rad: number): mat3 /** * Creates a matrix from a vector scaling @@ -2024,7 +2024,7 @@ export class mat3 extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat3} out */ - public static fromScaling(out: mat3, v: vec2): mat3 + public static fromScaling(out: mat3, v: vec2 | number[]): mat3 /** * Copies the values from a mat2d into a mat3 @@ -2061,7 +2061,7 @@ export class mat3 extends Float32Array { * @param mat matrix to represent as a string * @returns string representation of the matrix */ - public static str(mat: mat3):string; + public static str(mat: mat3): string; /** * Returns Frobenius norm of a mat3 @@ -2069,7 +2069,7 @@ export class mat3 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a: mat3):number; + public static frob(a: mat3): number; /** * Adds two mat3's @@ -2109,7 +2109,7 @@ export class mat3 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat3} out */ - public static multiplyScalar(out: mat3, a: mat3, b:number): mat3 + public static multiplyScalar(out: mat3, a: mat3, b: number): mat3 /** * Adds two mat3's after multiplying each element of the second operand by a scalar value. @@ -2120,7 +2120,7 @@ export class mat3 extends Float32Array { * @param {number} scale the amount to scale b's elements by before adding * @returns {mat3} out */ - public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale:number): mat3 + public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale: number): mat3 /** * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) @@ -2129,7 +2129,7 @@ export class mat3 extends Float32Array { * @param {mat3} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals(a: mat3, b: mat3):boolean; + public static exactEquals(a: mat3, b: mat3): boolean; /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -2138,12 +2138,12 @@ export class mat3 extends Float32Array { * @param {mat3} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals(a: mat3, b: mat3):boolean + public static equals(a: mat3, b: mat3): boolean } // mat4 export class mat4 extends Float32Array { - private typeMat4:number; + private typeMat4: number; /** * Creates a new identity mat4 @@ -2191,7 +2191,7 @@ export class mat4 extends Float32Array { * @param {number} m33 Component in column 3, row 3 position (index 15) * @returns {mat4} A new mat4 */ - public static fromValues(m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number): mat4; + public static fromValues(m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; /** * Set the components of a mat4 to the given values @@ -2215,7 +2215,7 @@ export class mat4 extends Float32Array { * @param {number} m33 Component in column 3, row 3 position (index 15) * @returns {mat4} out */ - public static set(out: mat4, m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number): mat4; + public static set(out: mat4, m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; /** * Set a mat4 to the identity matrix @@ -2258,7 +2258,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a: mat4):number; + public static determinant(a: mat4): number; /** * Multiplies two mat4's @@ -2288,7 +2288,7 @@ export class mat4 extends Float32Array { * @param v vector to translate by * @returns out */ - public static translate(out: mat4, a: mat4, v: vec3): mat4; + public static translate(out: mat4, a: mat4, v: vec3 | number[]): mat4; /** * Scales the mat4 by the dimensions in the given vec3 @@ -2298,7 +2298,7 @@ export class mat4 extends Float32Array { * @param v the vec3 to scale the matrix by * @returns out **/ - public static scale(out: mat4, a: mat4, v: vec3): mat4; + public static scale(out: mat4, a: mat4, v: vec3 | number[]): mat4; /** * Rotates a mat4 by the given angle @@ -2309,7 +2309,7 @@ export class mat4 extends Float32Array { * @param axis the axis to rotate around * @returns out */ - public static rotate(out: mat4, a: mat4, rad:number, axis: vec3): mat4; + public static rotate(out: mat4, a: mat4, rad: number, axis: vec3 | number[]): mat4; /** * Rotates a matrix by the given angle around the X axis @@ -2319,7 +2319,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateX(out: mat4, a: mat4, rad:number): mat4; + public static rotateX(out: mat4, a: mat4, rad: number): mat4; /** * Rotates a matrix by the given angle around the Y axis @@ -2329,7 +2329,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateY(out: mat4, a: mat4, rad:number): mat4; + public static rotateY(out: mat4, a: mat4, rad: number): mat4; /** * Rotates a matrix by the given angle around the Z axis @@ -2339,7 +2339,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateZ(out: mat4, a: mat4, rad:number): mat4; + public static rotateZ(out: mat4, a: mat4, rad: number): mat4; /** * Creates a matrix from a vector translation @@ -2352,7 +2352,7 @@ export class mat4 extends Float32Array { * @param {vec3} v Translation vector * @returns {mat4} out */ - public static fromTranslation(out: mat4, v: vec3): mat4 + public static fromTranslation(out: mat4, v: vec3 | number[]): mat4 /** * Creates a matrix from a vector scaling @@ -2365,7 +2365,7 @@ export class mat4 extends Float32Array { * @param {vec3} v Scaling vector * @returns {mat4} out */ - public static fromScaling(out: mat4, v: vec3): mat4 + public static fromScaling(out: mat4, v: vec3 | number[]): mat4 /** * Creates a matrix from a given angle around a given axis @@ -2379,7 +2379,7 @@ export class mat4 extends Float32Array { * @param {vec3} axis the axis to rotate around * @returns {mat4} out */ - public static fromRotation(out: mat4, rad:number, axis: vec3): mat4 + public static fromRotation(out: mat4, rad: number, axis: vec3 | number[]): mat4 /** * Creates a matrix from the given angle around the X axis @@ -2392,7 +2392,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromXRotation(out: mat4, rad:number): mat4 + public static fromXRotation(out: mat4, rad: number): mat4 /** * Creates a matrix from the given angle around the Y axis @@ -2405,7 +2405,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromYRotation(out: mat4, rad:number): mat4 + public static fromYRotation(out: mat4, rad: number): mat4 /** @@ -2419,7 +2419,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromZRotation(out: mat4, rad:number): mat4 + public static fromZRotation(out: mat4, rad: number): mat4 /** * Creates a matrix from a quaternion rotation and vector translation @@ -2436,7 +2436,7 @@ export class mat4 extends Float32Array { * @param v Translation vector * @returns out */ - public static fromRotationTranslation(out: mat4, q: quat, v: vec3): mat4; + public static fromRotationTranslation(out: mat4, q: quat, v: vec3 | number[]): mat4; /** * Returns the translation vector component of a transformation @@ -2477,7 +2477,7 @@ export class mat4 extends Float32Array { * @param s Scaling vector * @returns out */ - public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3, s: vec3): mat4; + public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[]): mat4; /** * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin @@ -2499,7 +2499,7 @@ export class mat4 extends Float32Array { * @param {vec3} o The origin vector around which to scale and rotate * @returns {mat4} out */ - public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3, s: vec3, o: vec3): mat4 + public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[], o: vec3 | number[]): mat4 /** * Calculates a 4x4 matrix from the given quaternion @@ -2523,8 +2523,8 @@ export class mat4 extends Float32Array { * @param far Far bound of the frustum * @returns out */ - public static frustum(out: mat4, left:number, right:number, - bottom:number, top:number, near:number, far:number): mat4; + public static frustum(out: mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): mat4; /** * Generates a perspective projection matrix with the given bounds @@ -2536,8 +2536,8 @@ export class mat4 extends Float32Array { * @param far Far bound of the frustum * @returns out */ - public static perspective(out: mat4, fovy:number, aspect:number, - near:number, far:number): mat4; + public static perspective(out: mat4, fovy: number, aspect: number, + near: number, far: number): mat4; /** * Generates a perspective projection matrix with the given field of view. @@ -2551,8 +2551,8 @@ export class mat4 extends Float32Array { * @returns {mat4} out */ public static perspectiveFromFieldOfView(out: mat4, - fov:{upDegrees:number, downDegrees:number, leftDegrees:number, rightDegrees:number}, - near:number, far:number): mat4 + fov:{upDegrees: number, downDegrees: number, leftDegrees: number, rightDegrees: number}, + near: number, far: number): mat4 /** * Generates a orthogonal projection matrix with the given bounds @@ -2566,8 +2566,8 @@ export class mat4 extends Float32Array { * @param far Far bound of the frustum * @returns out */ - public static ortho(out: mat4, left:number, right:number, - bottom:number, top:number, near:number, far:number): mat4; + public static ortho(out: mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): mat4; /** * Generates a look-at matrix with the given eye position, focal point, and up axis @@ -2578,7 +2578,7 @@ export class mat4 extends Float32Array { * @param up vec3 pointing up * @returns out */ - public static lookAt(out: mat4, eye: vec3, center: vec3, up: vec3): mat4; + public static lookAt(out: mat4, eye: vec3 | number[], center: vec3 | number[], up: vec3 | number[]): mat4; /** * Returns a string representation of a mat4 @@ -2586,7 +2586,7 @@ export class mat4 extends Float32Array { * @param mat matrix to represent as a string * @returns string representation of the matrix */ - public static str(mat: mat4):string; + public static str(mat: mat4): string; /** * Returns Frobenius norm of a mat4 @@ -2594,7 +2594,7 @@ export class mat4 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a: mat4):number; + public static frob(a: mat4): number; /** * Adds two mat4's @@ -2634,7 +2634,7 @@ export class mat4 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat4} out */ - public static multiplyScalar(out: mat4, a: mat4, b:number): mat4 + public static multiplyScalar(out: mat4, a: mat4, b: number): mat4 /** * Adds two mat4's after multiplying each element of the second operand by a scalar value. @@ -2645,7 +2645,7 @@ export class mat4 extends Float32Array { * @param {number} scale the amount to scale b's elements by before adding * @returns {mat4} out */ - public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale:number): mat4 + public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale: number): mat4 /** * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) @@ -2654,7 +2654,7 @@ export class mat4 extends Float32Array { * @param {mat4} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals (a: mat4, b: mat4) :boolean + public static exactEquals (a: mat4, b: mat4): boolean /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -2669,7 +2669,7 @@ export class mat4 extends Float32Array { // quat export class quat extends Float32Array { - private typeQuat:number; + private typeQuat: number; /** * Creates a new identity quat @@ -2730,18 +2730,6 @@ export class quat extends Float32Array { */ public static identity(out: quat): quat; - /** - * Sets the specified quaternion with values corresponding to the given - * axes. Each axis is a vec3 and is expected to be unit length and - * perpendicular to all other specified axes. - * - * @param {vec3} view the vector representing the viewing direction - * @param {vec3} right the vector representing the local "right" direction - * @param {vec3} up the vector representing the local "up" direction - * @returns {quat} out - */ - public static setAxes (out: quat, view: vec3, right: vec3, up: vec3): quat - /** * Sets a quaternion to represent the shortest rotation from one * vector to another. @@ -2753,7 +2741,19 @@ export class quat extends Float32Array { * @param {vec3} b the destination vector * @returns {quat} out */ - public static rotationTo (out: quat, a: vec3, b: vec3): quat; + public static rotationTo (out: quat, a: vec3 | number[], b: vec3 | number[]): quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} view the vector representing the viewing direction + * @param {vec3} right the vector representing the local "right" direction + * @param {vec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + public static setAxes (out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat @@ -2766,7 +2766,7 @@ export class quat extends Float32Array { * @param rad the angle in radians * @returns out **/ - public static setAxisAngle(out: quat, axis: vec3, rad: number): quat; + public static setAxisAngle(out: quat, axis: vec3 | number[], rad: number): quat; /** * Gets the rotation axis and angle for a given @@ -2781,7 +2781,7 @@ export class quat extends Float32Array { * @param {quat} q Quaternion to be decomposed * @return {number} Angle, in radians, of the rotation */ - public static getAxisAngle (out_axis: vec3, q: quat) :number + public static getAxisAngle (out_axis: vec3 | number[], q: quat): number /** * Adds two quat's @@ -2902,7 +2902,7 @@ export class quat extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static slerp(out: quat, a: quat, b: quat, t:number): quat; + public static slerp(out: quat, a: quat, b: quat, t: number): quat; /** * Performs a spherical linear interpolation with two control points @@ -2998,7 +2998,7 @@ export class quat extends Float32Array { * @param up the vector representing the local "up" direction * @returns out */ - public static setAxes(out: quat, view: vec3, right: vec3, up: vec3): quat; + public static setAxes(out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat; /** * Sets a quaternion to represent the shortest rotation from one @@ -3011,7 +3011,7 @@ export class quat extends Float32Array { * @param b the destination vector * @returns out */ - public static rotationTo(out: quat, a: vec3, b: vec3): quat; + public static rotationTo(out: quat, a: vec3 | number[], b: vec3 | number[]): quat; /** * Calculates the W component of a quat from the X, Y, and Z components. @@ -3031,7 +3031,7 @@ export class quat extends Float32Array { * @param {quat} b The second vector. * @returns {boolean} True if the quaternions are equal, false otherwise. */ - public static exactEquals (a: quat, b: quat) : boolean; + public static exactEquals (a: quat, b: quat): boolean; /** * Returns whether or not the quaternions have approximately the same elements in the same position. @@ -3040,5 +3040,5 @@ export class quat extends Float32Array { * @param {quat} b The second vector. * @returns {boolean} True if the quaternions are equal, false otherwise. */ - public static equals (a: quat, b: quat) : boolean; + public static equals (a: quat, b: quat): boolean; } From 3fbffb91e3837db19fa35ee4617317f9ed3e9370 Mon Sep 17 00:00:00 2001 From: Mattijs Kneppers Date: Mon, 15 Aug 2016 18:13:26 +0200 Subject: [PATCH 036/844] rename old implementation to legacy and new to standard --- gl-matrix/gl-matrix-legacy-tests.ts | 362 ++++ gl-matrix/gl-matrix-legacy.d.ts | 2163 +++++++++++++++++++ gl-matrix/gl-matrix-tests.ts | 653 +++--- gl-matrix/gl-matrix-typed-tests.ts | 347 --- gl-matrix/gl-matrix-typed.d.ts | 3044 --------------------------- gl-matrix/gl-matrix.d.ts | 1697 +++++++++++---- 6 files changed, 4133 insertions(+), 4133 deletions(-) create mode 100644 gl-matrix/gl-matrix-legacy-tests.ts create mode 100644 gl-matrix/gl-matrix-legacy.d.ts delete mode 100644 gl-matrix/gl-matrix-typed-tests.ts delete mode 100644 gl-matrix/gl-matrix-typed.d.ts diff --git a/gl-matrix/gl-matrix-legacy-tests.ts b/gl-matrix/gl-matrix-legacy-tests.ts new file mode 100644 index 0000000000..5cfa9a1c3a --- /dev/null +++ b/gl-matrix/gl-matrix-legacy-tests.ts @@ -0,0 +1,362 @@ +/// + +// common +var result: number = glMatrix.toRadian(180); + +var out: GLM.IArray; +var outVal: number; +var outStr: string; + +// vec2 +var vecA: GLM.IArray, vecB: GLM.IArray, matA: GLM.IArray; +var vecArray: GLM.IArray; + +vecA = [1, 2]; +vecB = new Float32Array([3, 4]); +out = [0, 0]; +matA = [1, 2, 3, 4, 5, 6]; +vecArray = [1, 2, 3, 4, 0, 0]; + +out = vec2.create(); +out = vec2.clone(vecA); +out = vec2.fromValues(1, 2); +out = vec2.copy(out, vecA); +out = vec2.set(out, 1, 2); +out = vec2.add(out, vecA, vecB); +out = vec2.subtract(out, vecA, vecB); +out = vec2.sub(out, vecA, vecB); +out = vec2.multiply(out, vecA, vecB); +out = vec2.mul(out, vecA, vecB); +out = vec2.divide(out, vecA, vecB); +out = vec2.div(out, vecA, vecB); +out = vec2.min(out, vecA, vecB); +out = vec2.max(out, vecA, vecB); +out = vec2.scale(out, vecA, 2); +out = vec2.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec2.distance(vecA, vecB); +outVal = vec2.dist(vecA, vecB); +outVal = vec2.squaredDistance(vecA, vecB); +outVal = vec2.sqrDist(vecA, vecB); +outVal = vec2.length(vecA); +outVal = vec2.len(vecA); +outVal = vec2.squaredLength(vecA); +outVal = vec2.sqrLen(vecA); +out = vec2.negate(out, vecA); +out = vec2.inverse(out, vecA); +out = vec2.normalize(out, vecA); +outVal = vec2.dot(vecA, vecB); +out = vec2.cross(out, vecA, vecB); +out = vec2.lerp(out, vecA, vecB, 0.5); +out = vec2.random(out); +out = vec2.random(out, 5.0); +out = vec2.transformMat2(out, vecA, matA); +out = vec2.transformMat2d(out, vecA, matA); +out = vec2.transformMat3(out, vecA, matA); +out = vec2.transformMat4(out, vecA, matA); +out = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); +outStr = vec2.str(vecA); + +// vec3 +var matr: GLM.IArray; +var q: GLM.IArray; + +vecA = [1, 2, 3]; +vecB = new Float32Array([4, 5, 6]); +out = [0, 0, 0]; +vecArray = [1, 2, 3, 4, 5, 6, 0, 0, 0]; +matr = [1, 0, 0, 0, 1, 0, 0, 0, 1 ]; + +out = vec3.create(); +out = vec3.clone(vecA); +out = vec3.fromValues(1, 2, 3); +out = vec3.copy(out, vecA); +out = vec3.set(out, 1, 2, 3); +out = vec3.add(out, vecA, vecB); +out = vec3.subtract(out, vecA, vecB); +out = vec3.sub(out, vecA, vecB); +out = vec3.multiply(out, vecA, vecB); +out = vec3.mul(out, vecA, vecB); +out = vec3.divide(out, vecA, vecB); +out = vec3.div(out, vecA, vecB); +out = vec3.min(out, vecA, vecB); +out = vec3.max(out, vecA, vecB); +out = vec3.scale(out, vecA, 2); +out = vec3.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec3.distance(vecA, vecB); +outVal = vec3.dist(vecA, vecB); +outVal = vec3.squaredDistance(vecA, vecB); +outVal = vec3.sqrDist(vecA, vecB); +outVal = vec3.length(vecA); +outVal = vec3.len(vecA); +outVal = vec3.squaredLength(vecA); +outVal = vec3.sqrLen(vecA); +out = vec3.negate(out, vecA); +out = vec3.inverse(out, vecA); +out = vec3.normalize(out, vecA); +outVal = vec3.dot(vecA, vecB); +out = vec3.cross(out, vecA, vecB); +out = vec3.lerp(out, vecA, vecB, 0.5); +out = vec3.random(out); +out = vec3.random(out, 5.0); +out = vec3.rotateX(out, vecA, vecB, Math.PI); +out = vec3.rotateY(out, vecA, vecB, Math.PI); +out = vec3.rotateZ(out, vecA, vecB, Math.PI); +out = vec3.transformMat3(out, vecA, matr); + +matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; +out = vec3.transformMat4(out, vecA, matr); + +q = [1, 2, 3, 4]; +out = vec3.transformQuat(out, vecA, matr); + +out = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); +outVal = vec3.angle(vecA, vecB); +outStr = vec3.str(vecA); + +// vec4 +var q: GLM.IArray; + +vecA = [1, 2, 3, 4]; +vecB = new Float32Array([5, 6, 7, 8]); +out = [0, 0, 0, 0]; +q = [1, 2, 3, 4]; + +out = vec4.create(); +out = vec4.clone(vecA); +out = vec4.fromValues(1, 2, 3, 4); +out = vec4.copy(out, vecA); +out = vec4.set(out, 1, 2, 3, 4); +out = vec4.add(out, vecA, vecB); +out = vec4.subtract(out, vecA, vecB); +out = vec4.sub(out, vecA, vecB); +out = vec4.multiply(out, vecA, vecB); +out = vec4.mul(out, vecA, vecB); +out = vec4.divide(out, vecA, vecB); +out = vec4.div(out, vecA, vecB); +out = vec4.min(out, vecA, vecB); +out = vec4.max(out, vecA, vecB); +out = vec4.scale(out, vecA, 2); +out = vec4.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec4.distance(vecA, vecB); +outVal = vec4.dist(vecA, vecB); +outVal = vec4.squaredDistance(vecA, vecB); +outVal = vec4.sqrDist(vecA, vecB); +outVal = vec4.length(vecA); +outVal = vec4.len(vecA); +outVal = vec4.squaredLength(vecA); +outVal = vec4.sqrLen(vecA); +out = vec4.negate(out, vecA); +out = vec4.inverse(out, vecA); +out = vec4.normalize(out, vecA); +outVal = vec4.dot(vecA, vecB); +out = vec4.lerp(out, vecA, vecB, 0.5); +out = vec4.random(out); +out = vec4.random(out, 5.0); + +matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] +out = vec4.transformMat4(out, vecA, matr); +out = vec4.transformQuat(out, vecA, q); + +vecArray = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0]; +out = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); +outStr = vec4.str(vecA); + +// mat2 +var matB: GLM.IArray, identity: GLM.IArray; + +matA = [1, 2, 3, 4]; +matB = new Float32Array([5, 6, 7, 8]); +out = [0, 0, 0, 0]; +identity = [1, 0, 0, 1]; + +out = mat2.create(); +out = mat2.clone(matA); +out = mat2.copy(out, matA); +out = mat2.identity(out); +out = mat2.transpose(out, matA); +out = mat2.invert(out, matA); +out = mat2.adjoint(out, matA); +outVal = mat2.determinant(matA); +out = mat2.multiply(out, matA, matB); +out = mat2.mul(out, matA, matB); +out = mat2.rotate(out, matA, Math.PI * 0.5); + +vecA = [2, 3]; +out = mat2.scale(out, matA, vecA); +outStr = mat2.str(matA); +outVal = mat2.frob(matA); + +var L = mat2.create(); +var D = mat2.create(); +var U = mat2.create(); +out = mat2.LDU(L, D, U, [4,3,6,3]); + +// mat2d +matA = [1, 2, 3, 4, 5, 6]; +matB = [7, 8, 9, 10, 11, 12]; +out = [0, 0, 0, 0, 0, 0]; +identity = [1, 0, 0, 1, 0, 0]; + +out = mat2d.create(); +out = mat2d.clone(matA); +out = mat2d.copy(out, matA); +out = mat2d.identity(out); +out = mat2d.invert(out, matA); +outVal = mat2d.determinant(matA); +out = mat2d.multiply(out, matA, matB); +out = mat2d.mul(out, matA, matB); +out = mat2d.rotate(out, matA, Math.PI * 0.5); + +vecA = [2, 3]; +out = mat2d.scale(out, matA, vecA); +out = mat2d.translate(out, matA, vecA); +outStr = mat2d.str(matA); +outVal = mat2d.frob(matA); + +// mat3 +matA = [1, 0, 0, 0, 1, 0, 1, 2, 1]; +matB = [1, 0, 0, 0, 1, 0, 3, 4, 1]; +out = [0, 0, 0, 0, 0, 0, 0, 0, 0]; +identity = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + +out = mat3.create(); +out = mat3.clone(matA); +out = mat3.copy(out, matA); +out = mat3.identity(out); +out = mat3.transpose(out, matA); +out = mat3.invert(out, matA); +out = mat3.adjoint(out, matA); +outVal = mat3.determinant(matA); +out = mat3.multiply(out, matA, matB); +out = mat3.mul(out, matA, matB); +outStr = mat3.str(matA); +outVal = mat3.frob(matA); + +matA = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]; +out = mat3.normalFromMat4(out, matA); + +q = [ 0, -0.7071067811865475, 0, 0.7071067811865475 ]; +out = mat3.fromQuat(out, q); + +out = mat3.normalFromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); +out = mat3.fromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); +out = mat3.scale(out, matA, [2,2]); +out = mat3.fromMat2d(out, [1, 2, 3, 4, 5, 6]); + +out = mat3.translate(out, matA, [1, 2, 3]); +out = mat3.rotate(out, matA, Math.PI/2); + +// mat4 +matA = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 1, 2, 3, 1]; + +matB = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 4, 5, 6, 1]; + +out = [0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0]; + +identity = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]; + +out = mat4.create(); +out = mat4.clone(matA); +out = mat4.copy(out, matA); +out = mat4.identity(out); +out = mat4.transpose(out, matA); +out = mat4.invert(out, matA); +out = mat4.adjoint(out, matA); +outVal = mat4.determinant(matA); +out = mat4.multiply(out, matA, matB); +out = mat4.mul(out, matA, matB); +out = mat4.translate(out, matA, [4, 5, 6]); +out = mat4.scale(out, matA, [4, 5, 6]); + +var rad = Math.PI * 0.5; +var axis = [1, 0, 0]; +out = mat4.rotate(out, matA, rad, axis); +out = mat4.rotateX(out, matA, rad); +out = mat4.rotateY(out, matA, rad); +out = mat4.rotateZ(out, matA, rad); + +out = mat4.frustum(out, -1, 1, -1, 1, -1, 1); + +var fovy = Math.PI * 0.5; +out = mat4.perspective(out, fovy, 1, 0, 1); +out = mat4.ortho(out, -1, 1, -1, 1, -1, 1); + +var eye = [0, 0, 1]; +var center = [0, 0, -1]; +var up = [0, 1, 0]; +out = mat4.lookAt(out, eye, center, up); + +outStr = mat4.str(matA); +outVal = mat4.frob(matA); + +q = [0, 0, 0, 1]; +out = mat4.fromRotationTranslation(out, q, [1, 2, 3]); +out = mat4.fromQuat(out, q); + +q = [0, 0, 0, 1]; +out = mat4.fromRotationTranslationScale(out, q, [1, 2, 3], [1, 2, 3]); +out = mat4.fromQuat(out, q); + + +// quat +var quatA = [1, 2, 3, 4]; +var quatB = [5, 6, 7, 8]; +out = [0, 0, 0, 0]; +var vec = [1, 1, -1]; +var id = [0, 0, 0, 1]; +var deg90 = Math.PI / 2; + +out = quat.create(); +out = quat.clone(quatA); +out = quat.fromValues(1, 2, 3, 4); +out = quat.copy(out, quatA); +out = quat.set(out, 1, 2, 3, 4); +out = quat.identity(out); +out = quat.setAxisAngle(out, [1, 0, 0], Math.PI * 0.5); +out = quat.add(out, quatA, quatB); +out = quat.multiply(out, quatA, quatB); +out = quat.mul(out, quatA, quatB); +out = quat.scale(out, quatA, 2); +outVal = quat.length(quatA); +outVal = quat.len(quatA); +outVal = quat.squaredLength(quatA); +outVal = quat.sqrLen(quatA); +out = quat.normalize(out, quatA); +outVal = quat.dot(out, quatA, quatB); +out = quat.lerp(out, quatA, quatB, 0.5); +out = quat.slerp(out, quatA, quatB, 0.5); +out = quat.invert(out, quatA); +out = quat.conjugate(out, quatA); +outStr = quat.str(quatA); +out = quat.rotateX(out, id, deg90); +out = quat.rotateY(out, id, deg90); +out = quat.rotateZ(out, id, deg90); + +matr = [ 1, 0, 0, + 0, 0, -1, + 0, 1, 0 ]; +out = quat.fromMat3(out, matr); + +var view = [-1, 0, 0]; +up = [ 0, 1, 0]; +var right= [ 0, 0,-1]; +out = quat.setAxes([], view, right, up); + +out = quat.rotationTo(out, [0, 1, 0], [1, 0, 0]); +out = quat.calculateW(out, quatA); + diff --git a/gl-matrix/gl-matrix-legacy.d.ts b/gl-matrix/gl-matrix-legacy.d.ts new file mode 100644 index 0000000000..16366f263a --- /dev/null +++ b/gl-matrix/gl-matrix-legacy.d.ts @@ -0,0 +1,2163 @@ +// Type definitions for gl-matrix 2.2.2 +// Project: https://github.com/toji/gl-matrix +// Definitions by: Tat +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace GLM { + interface IArray + { + /** + * Must be indexable like an array + */ + [index: number]: number; + } +} + +// Common +declare namespace glMatrix { + /** + * Convert Degree To Radian + * + * @param a Angle in Degrees + */ + export function toRadian(a: number): number; +} + +// vec2 +declare namespace vec2 { + /** + * Creates a new, empty vec2 + * + * @returns a new 2D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec2 initialized with values from an existing vector + * + * @param a a vector to clone + * @returns a new 2D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new vec2 initialized with the given values + * + * @param x X component + * @param y Y component + * @returns a new 2D vector + */ + export function fromValues(x: number, y: number): GLM.IArray; + + /** + * Copy the values from one vec2 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a vec2 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @returns out + */ + export function set(out: GLM.IArray, x: number, y: number): GLM.IArray; + + /** + * Adds two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a vec2 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function dist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec2 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec2 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec2 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + export function dot(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Performs a linear interpolation between two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * Transforms the vec2 with a mat2 + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat2(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec2 with a mat2d + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat2d(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + */ + export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + */ + export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// vec3 +declare namespace vec3 { + + /** + * Creates a new, empty vec3 + * + * @returns a new 3D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec3 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 3D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new vec3 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @returns a new 3D vector + */ + export function fromValues(x: number, y: number, z: number): GLM.IArray; + + /** + * Copy the values from one vec3 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a vec3 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @returns out + */ + export function set(out: GLM.IArray, x: number, y: number, z: number): GLM.IArray; + + /** + * Adds two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a vec3 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function dist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec3 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec3 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec3 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + export function dot(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Computes the cross product of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Performs a linear interpolation between two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * Rotate a 3D vector around the x-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * Rotate a 3D vector around the y-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * Rotate a 3D vector around the z-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * Transforms the vec3 with a mat3. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m the 3x3 matrix to transform with + * @returns out + */ + export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec3 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + export function transformQuat(out: GLM.IArray, a: GLM.IArray, q: GLM.IArray): GLM.IArray; + + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Get the angle between two 3D vectors + * @param a The first operand + * @param b The second operand + * @returns The angle in radians + */ + export function angle(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// vec4 +declare namespace vec4 { + + /** + * Creates a new, empty vec4 + * + * @returns a new 4D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec4 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 4D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new vec4 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new 4D vector + */ + export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Copy the values from one vec4 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a vec4 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + */ + export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Adds two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a vec4 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function dist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec4 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec4 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec4 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + export function dot(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Performs a linear interpolation between two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * Transforms the vec4 with a mat4. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, mat: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec4 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + export function transformQuat(out: GLM.IArray, a: GLM.IArray, quat: GLM.IArray): GLM.IArray; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param additional argument to pass to fn + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + callback: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + callback: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// mat2 +declare namespace mat2 { + + /** + * Creates a new identity mat2 + * + * @returns a new 2x2 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x2 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat2 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat2 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat2 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat2 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat2 + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(a: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat2 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; + + /** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param L the lower triangular matrix + * @param D the diagonal matrix + * @param U the upper triangular matrix + * @param a the input matrix to factorize + */ + export function LDU(L: GLM.IArray, D: GLM.IArray, U: GLM.IArray, a: GLM.IArray): GLM.IArray; +} + +// mat2d +declare namespace mat2d { + + /** + * Creates a new identity mat2d + * + * @returns a new 2x3 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x3 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat2d to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat2d to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat2d + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat2d + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat2d by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Scales the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Translates the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to translate the matrix by + * @returns out + **/ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat2d + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(a: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat2d + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; +} + +// mat3 +declare namespace mat3 { + + /** + * Creates a new identity mat3 + * + * @returns a new 3x3 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 3x3 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat3 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat3 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat3 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat3 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(mat: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat3 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; + + /** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param out mat3 receiving operation result + * @param a Mat4 to derive the normal matrix from + * + * @returns out + */ + export function normalFromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates a 3x3 matrix from the given quaternion + * + * @param out mat3 receiving operation result + * @param q Quaternion to create matrix from + * + * @returns out + */ + export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; + + /** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param out the receiving 3x3 matrix + * @param a the source 4x4 matrix + * @returns out + */ + export function fromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Copies the values from a mat2d into a mat3 + * + * @param out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns out + **/ + export function fromMat2d(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Translate a mat3 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat3 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; +} + +// mat4 +declare namespace mat4 { + + /** + * Creates a new identity mat4 + * + * @returns a new 4x4 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 4x4 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat4 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat4 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(a: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat4 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Translate a mat4 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param out the receiving matrix + * @param a the matrix to scale + * @param v the vec3 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat4 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @param axis the axis to rotate around + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number, axis: GLM.IArray): GLM.IArray; + + /** + * Rotates a matrix by the given angle around the X axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a matrix by the given angle around the Y axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a matrix by the given angle around the Z axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Generates a frustum matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + export function frustum(out: GLM.IArray, left: number, right: number, + bottom: number, top: number, near: number, far: number): GLM.IArray; + + /** + * Generates a perspective projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param fovy Vertical field of view in radians + * @param aspect Aspect ratio. typically viewport width/height + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + export function perspective(out: GLM.IArray, fovy: number, aspect: number, + near: number, far: number): GLM.IArray; + + /** + * Generates a orthogonal projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + export function ortho(out: GLM.IArray, left: number, right: number, + bottom: number, top: number, near: number, far: number): GLM.IArray; + + /** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param out mat4 frustum matrix will be written into + * @param eye Position of the viewer + * @param center Point the viewer is looking at + * @param up vec3 pointing up + * @returns out + */ + export function lookAt(out: GLM.IArray, eye: GLM.IArray, + center: GLM.IArray, up: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat4 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(mat: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat4 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; + + /** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @returns out + */ + export function fromRotationTranslation(out: GLM.IArray, q: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale. + * + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @param s Scale vector + * @returns out + */ + export function fromRotationTranslationScale(out: GLM.IArray, q: GLM.IArray, v: GLM.IArray, s: GLM.IArray): GLM.IArray + + /** + * Creates a matrix from a quaternion + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @returns out + */ + export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; +} + +// quat +declare namespace quat { + + /** + * Creates a new identity quat + * + * @returns a new quaternion + */ + export function create(): GLM.IArray; + + /** + * Creates a new quat initialized with values from an existing quaternion + * + * @param a quaternion to clone + * @returns a new quaternion + * @function + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new quat initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new quaternion + * @function + */ + export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Copy the values from one quat to another + * + * @param out the receiving quaternion + * @param a the source quaternion + * @returns out + * @function + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a quat to the given values + * + * @param out the receiving quaternion + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + * @function + */ + export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Set a quat to the identity quaternion + * + * @param out the receiving quaternion + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param out the receiving quaternion + * @param axis the axis around which to rotate + * @param rad the angle in radians + * @returns out + **/ + export function setAxisAngle(out: GLM.IArray, axis: GLM.IArray, rad: number): GLM.IArray; + + /** + * Adds two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + * @function + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a quat by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + * @function + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Normalize a quat + * + * @param out the receiving quaternion + * @param a quaternion to normalize + * @returns out + * @function + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two quat's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + * @function + */ + export function dot(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): number; + + /** + * Performs a linear interpolation between two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + * @function + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Performs a spherical linear interpolation between two quat + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function slerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Calculates the inverse of a quat + * + * @param out the receiving quaternion + * @param a quat to calculate inverse of + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param out the receiving quaternion + * @param a quat to calculate conjugate of + * @returns out + */ + export function conjugate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a quatenion + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; + + /** + * Rotates a quaternion by the given angle about the X axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a quaternion by the given angle about the Y axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a quaternion by the given angle about the Z axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param out the receiving quaternion + * @param m rotation matrix + * @returns out + * @function + */ + export function fromMat3(out: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param view the vector representing the viewing direction + * @param right the vector representing the local "right" direction + * @param up the vector representing the local "up" direction + * @returns out + */ + export function setAxes(out: GLM.IArray, view: GLM.IArray, right: GLM.IArray, + up: GLM.IArray): GLM.IArray; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param out the receiving quaternion. + * @param a the initial vector + * @param b the destination vector + * @returns out + */ + export function rotationTo(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param out the receiving quaternion + * @param a quat to calculate W component of + * @returns out + */ + export function calculateW(out: GLM.IArray, a: GLM.IArray): GLM.IArray; +} diff --git a/gl-matrix/gl-matrix-tests.ts b/gl-matrix/gl-matrix-tests.ts index 682bca7b8b..984ca3d1c3 100644 --- a/gl-matrix/gl-matrix-tests.ts +++ b/gl-matrix/gl-matrix-tests.ts @@ -1,362 +1,347 @@ /// // common -var result: number = glMatrix.toRadian(180); +import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "./gl-matrix"; -var out: GLM.IArray; var outVal: number; +var outBool: boolean; var outStr: string; +let vecArray = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + +let vec2A = vec2.fromValues(1, 2); +let vec2B = vec2.fromValues(3, 4); +let vec3A = vec3.fromValues(1, 2, 3); +let vec3B = vec3.fromValues(3, 4, 5); +let vec4A = vec4.fromValues(1, 2, 3, 4); +let vec4B = vec4.fromValues(3, 4, 5, 6); +let mat2A = mat2.fromValues(1, 2, 3, 4); +let mat2B = mat2.fromValues(1, 2, 3, 4); +let mat2dA = mat2d.fromValues(1, 2, 3, 4, 5, 6); +let mat2dB = mat2d.fromValues(1, 2, 3, 4, 5, 6); +let mat3A = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +let mat3B = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +let mat4A = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +let mat4B = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +let quatA = quat.fromValues(1, 2, 3, 4); +let quatB = quat.fromValues(5, 6, 7, 8); + +let outVec2 = vec2.create(); +let outVec3 = vec3.create(); +let outVec4 = vec4.create(); +let outMat2 = mat2.create(); +let outMat2d = mat2d.create(); +let outMat3 = mat3.create(); +let outMat4 = mat4.create(); +let outQuat = quat.create(); + // vec2 -var vecA: GLM.IArray, vecB: GLM.IArray, matA: GLM.IArray; -var vecArray: GLM.IArray; - -vecA = [1, 2]; -vecB = new Float32Array([3, 4]); -out = [0, 0]; -matA = [1, 2, 3, 4, 5, 6]; -vecArray = [1, 2, 3, 4, 0, 0]; - -out = vec2.create(); -out = vec2.clone(vecA); -out = vec2.fromValues(1, 2); -out = vec2.copy(out, vecA); -out = vec2.set(out, 1, 2); -out = vec2.add(out, vecA, vecB); -out = vec2.subtract(out, vecA, vecB); -out = vec2.sub(out, vecA, vecB); -out = vec2.multiply(out, vecA, vecB); -out = vec2.mul(out, vecA, vecB); -out = vec2.divide(out, vecA, vecB); -out = vec2.div(out, vecA, vecB); -out = vec2.min(out, vecA, vecB); -out = vec2.max(out, vecA, vecB); -out = vec2.scale(out, vecA, 2); -out = vec2.scaleAndAdd(out, vecA, vecB, 0.5); -outVal = vec2.distance(vecA, vecB); -outVal = vec2.dist(vecA, vecB); -outVal = vec2.squaredDistance(vecA, vecB); -outVal = vec2.sqrDist(vecA, vecB); -outVal = vec2.length(vecA); -outVal = vec2.len(vecA); -outVal = vec2.squaredLength(vecA); -outVal = vec2.sqrLen(vecA); -out = vec2.negate(out, vecA); -out = vec2.inverse(out, vecA); -out = vec2.normalize(out, vecA); -outVal = vec2.dot(vecA, vecB); -out = vec2.cross(out, vecA, vecB); -out = vec2.lerp(out, vecA, vecB, 0.5); -out = vec2.random(out); -out = vec2.random(out, 5.0); -out = vec2.transformMat2(out, vecA, matA); -out = vec2.transformMat2d(out, vecA, matA); -out = vec2.transformMat3(out, vecA, matA); -out = vec2.transformMat4(out, vecA, matA); -out = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); -outStr = vec2.str(vecA); +outVec2 = vec2.create(); +outVec2 = vec2.clone(vec2A); +outVec2 = vec2.fromValues(1, 2); +outVec2 = vec2.copy(outVec2, vec2A); +outVec2 = vec2.set(outVec2, 1, 2); +outVec2 = vec2.add(outVec2, vec2A, vec2B); +outVec2 = vec2.subtract(outVec2, vec2A, vec2B); +outVec2 = vec2.sub(outVec2, vec2A, vec2B); +outVec2 = vec2.multiply(outVec2, vec2A, vec2B); +outVec2 = vec2.mul(outVec2, vec2A, vec2B); +outVec2 = vec2.divide(outVec2, vec2A, vec2B); +outVec2 = vec2.div(outVec2, vec2A, vec2B); +outVec2 = vec2.ceil(outVec2, vec2A); +outVec2 = vec2.floor(outVec2, vec2A); +outVec2 = vec2.min(outVec2, vec2A, vec2B); +outVec2 = vec2.max(outVec2, vec2A, vec2B); +outVec2 = vec2.round(outVec2, vec2A); +outVec2 = vec2.scale(outVec2, vec2A, 2); +outVec2 = vec2.scaleAndAdd(outVec2, vec2A, vec2B, 0.5); +outVal = vec2.distance(vec2A, vec2B); +outVal = vec2.dist(vec2A, vec2B); +outVal = vec2.squaredDistance(vec2A, vec2B); +outVal = vec2.sqrDist(vec2A, vec2B); +outVal = vec2.length(vec2A); +outVal = vec2.len(vec2A); +outVal = vec2.squaredLength(vec2A); +outVal = vec2.sqrLen(vec2A); +outVec2 = vec2.negate(outVec2, vec2A); +outVec2 = vec2.inverse(outVec2, vec2A); +outVec2 = vec2.normalize(outVec2, vec2A); +outVal = vec2.dot(vec2A, vec2B); +outVec2 = vec2.cross(outVec2, vec2A, vec2B); +outVec2 = vec2.lerp(outVec2, vec2A, vec2B, 0.5); +outVec2 = vec2.random(outVec2); +outVec2 = vec2.random(outVec2, 5.0); +outVec2 = vec2.transformMat2(outVec2, vec2A, mat2A); +outVec2 = vec2.transformMat2d(outVec2, vec2A, mat2dA); +outVec2 = vec2.transformMat3(outVec2, vec2A, mat3A); +outVec2 = vec2.transformMat4(outVec2, vec2A, mat4A); +vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); +outStr = vec2.str(vec2A); +outBool = vec2.exactEquals(vec2A, vec2B); +outBool = vec2.equals(vec2A, vec2B); +outVec2 = vec2.add(outVec2, [0, 1], [2, 3]); // test one method with number array input // vec3 -var matr: GLM.IArray; -var q: GLM.IArray; - -vecA = [1, 2, 3]; -vecB = new Float32Array([4, 5, 6]); -out = [0, 0, 0]; -vecArray = [1, 2, 3, 4, 5, 6, 0, 0, 0]; -matr = [1, 0, 0, 0, 1, 0, 0, 0, 1 ]; - -out = vec3.create(); -out = vec3.clone(vecA); -out = vec3.fromValues(1, 2, 3); -out = vec3.copy(out, vecA); -out = vec3.set(out, 1, 2, 3); -out = vec3.add(out, vecA, vecB); -out = vec3.subtract(out, vecA, vecB); -out = vec3.sub(out, vecA, vecB); -out = vec3.multiply(out, vecA, vecB); -out = vec3.mul(out, vecA, vecB); -out = vec3.divide(out, vecA, vecB); -out = vec3.div(out, vecA, vecB); -out = vec3.min(out, vecA, vecB); -out = vec3.max(out, vecA, vecB); -out = vec3.scale(out, vecA, 2); -out = vec3.scaleAndAdd(out, vecA, vecB, 0.5); -outVal = vec3.distance(vecA, vecB); -outVal = vec3.dist(vecA, vecB); -outVal = vec3.squaredDistance(vecA, vecB); -outVal = vec3.sqrDist(vecA, vecB); -outVal = vec3.length(vecA); -outVal = vec3.len(vecA); -outVal = vec3.squaredLength(vecA); -outVal = vec3.sqrLen(vecA); -out = vec3.negate(out, vecA); -out = vec3.inverse(out, vecA); -out = vec3.normalize(out, vecA); -outVal = vec3.dot(vecA, vecB); -out = vec3.cross(out, vecA, vecB); -out = vec3.lerp(out, vecA, vecB, 0.5); -out = vec3.random(out); -out = vec3.random(out, 5.0); -out = vec3.rotateX(out, vecA, vecB, Math.PI); -out = vec3.rotateY(out, vecA, vecB, Math.PI); -out = vec3.rotateZ(out, vecA, vecB, Math.PI); -out = vec3.transformMat3(out, vecA, matr); - -matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; -out = vec3.transformMat4(out, vecA, matr); - -q = [1, 2, 3, 4]; -out = vec3.transformQuat(out, vecA, matr); - -out = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); -outVal = vec3.angle(vecA, vecB); -outStr = vec3.str(vecA); +outVec3 = vec3.create(); +outVec3 = vec3.clone(vec3A); +outVec3 = vec3.fromValues(1, 2, 3); +outVec3 = vec3.copy(outVec3, vec3A); +outVec3 = vec3.set(outVec3, 1, 2, 3); +outVec3 = vec3.add(outVec3, vec3A, vec3B); +outVec3 = vec3.subtract(outVec3, vec3A, vec3B); +outVec3 = vec3.sub(outVec3, vec3A, vec3B); +outVec3 = vec3.multiply(outVec3, vec3A, vec3B); +outVec3 = vec3.mul(outVec3, vec3A, vec3B); +outVec3 = vec3.divide(outVec3, vec3A, vec3B); +outVec3 = vec3.div(outVec3, vec3A, vec3B); +outVec3 = vec3.ceil(outVec3, vec3A); +outVec3 = vec3.floor(outVec3, vec3A); +outVec3 = vec3.min(outVec3, vec3A, vec3B); +outVec3 = vec3.max(outVec3, vec3A, vec3B); +outVec3 = vec3.round(outVec3, vec3A); +outVec3 = vec3.scale(outVec3, vec3A, 2); +outVec3 = vec3.scaleAndAdd(outVec3, vec3A, vec3B, 0.5); +outVal = vec3.distance(vec3A, vec3B); +outVal = vec3.dist(vec3A, vec3B); +outVal = vec3.squaredDistance(vec3A, vec3B); +outVal = vec3.sqrDist(vec3A, vec3B); +outVal = vec3.length(vec3A); +outVal = vec3.len(vec3A); +outVal = vec3.squaredLength(vec3A); +outVal = vec3.sqrLen(vec3A); +outVec3 = vec3.negate(outVec3, vec3A); +outVec3 = vec3.inverse(outVec3, vec3A); +outVec3 = vec3.normalize(outVec3, vec3A); +outVal = vec3.dot(vec3A, vec3B); +outVec3 = vec3.cross(outVec3, vec3A, vec3B); +outVec3 = vec3.lerp(outVec3, vec3A, vec3B, 0.5); +outVec3 = vec3.hermite(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); +outVec3 = vec3.bezier(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); +outVec3 = vec3.random(outVec3); +outVec3 = vec3.random(outVec3, 5.0); +outVec3 = vec3.transformMat3(outVec3, vec3A, mat3A); +outVec3 = vec3.transformMat4(outVec3, vec3A, mat4A); +outVec3 = vec3.transformQuat(outVec3, vec3A, quatA); +outVec3 = vec3.rotateX(outVec3, vec3A, vec3B, Math.PI); +outVec3 = vec3.rotateY(outVec3, vec3A, vec3B, Math.PI); +outVec3 = vec3.rotateZ(outVec3, vec3A, vec3B, Math.PI); +vecArray = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); +outVal = vec3.angle(vec3A, vec3B); +outStr = vec3.str(vec3A); +outBool = vec3.exactEquals(vec3A, vec3B); +outBool = vec3.equals(vec3A, vec3B); +outVec3 = vec3.add(outVec3, [0, 1, 2], [3, 4, 5]); // test one method with number array input // vec4 -var q: GLM.IArray; - -vecA = [1, 2, 3, 4]; -vecB = new Float32Array([5, 6, 7, 8]); -out = [0, 0, 0, 0]; -q = [1, 2, 3, 4]; - -out = vec4.create(); -out = vec4.clone(vecA); -out = vec4.fromValues(1, 2, 3, 4); -out = vec4.copy(out, vecA); -out = vec4.set(out, 1, 2, 3, 4); -out = vec4.add(out, vecA, vecB); -out = vec4.subtract(out, vecA, vecB); -out = vec4.sub(out, vecA, vecB); -out = vec4.multiply(out, vecA, vecB); -out = vec4.mul(out, vecA, vecB); -out = vec4.divide(out, vecA, vecB); -out = vec4.div(out, vecA, vecB); -out = vec4.min(out, vecA, vecB); -out = vec4.max(out, vecA, vecB); -out = vec4.scale(out, vecA, 2); -out = vec4.scaleAndAdd(out, vecA, vecB, 0.5); -outVal = vec4.distance(vecA, vecB); -outVal = vec4.dist(vecA, vecB); -outVal = vec4.squaredDistance(vecA, vecB); -outVal = vec4.sqrDist(vecA, vecB); -outVal = vec4.length(vecA); -outVal = vec4.len(vecA); -outVal = vec4.squaredLength(vecA); -outVal = vec4.sqrLen(vecA); -out = vec4.negate(out, vecA); -out = vec4.inverse(out, vecA); -out = vec4.normalize(out, vecA); -outVal = vec4.dot(vecA, vecB); -out = vec4.lerp(out, vecA, vecB, 0.5); -out = vec4.random(out); -out = vec4.random(out, 5.0); - -matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] -out = vec4.transformMat4(out, vecA, matr); -out = vec4.transformQuat(out, vecA, q); - -vecArray = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0]; -out = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); -outStr = vec4.str(vecA); +outVec4 = vec4.create(); +outVec4 = vec4.clone(vec4A); +outVec4 = vec4.fromValues(1, 2, 3, 4); +outVec4 = vec4.copy(outVec4, vec4A); +outVec4 = vec4.set(outVec4, 1, 2, 3, 4); +outVec4 = vec4.add(outVec4, vec4A, vec4B); +outVec4 = vec4.subtract(outVec4, vec4A, vec4B); +outVec4 = vec4.sub(outVec4, vec4A, vec4B); +outVec4 = vec4.multiply(outVec4, vec4A, vec4B); +outVec4 = vec4.mul(outVec4, vec4A, vec4B); +outVec4 = vec4.divide(outVec4, vec4A, vec4B); +outVec4 = vec4.div(outVec4, vec4A, vec4B); +outVec4 = vec4.ceil(outVec4, vec4A); +outVec4 = vec4.floor(outVec4, vec4A); +outVec4 = vec4.min(outVec4, vec4A, vec4B); +outVec4 = vec4.max(outVec4, vec4A, vec4B); +outVec4 = vec4.scale(outVec4, vec4A, 2); +outVec4 = vec4.scaleAndAdd(outVec4, vec4A, vec4B, 0.5); +outVal = vec4.distance(vec4A, vec4B); +outVal = vec4.dist(vec4A, vec4B); +outVal = vec4.squaredDistance(vec4A, vec4B); +outVal = vec4.sqrDist(vec4A, vec4B); +outVal = vec4.length(vec4A); +outVal = vec4.len(vec4A); +outVal = vec4.squaredLength(vec4A); +outVal = vec4.sqrLen(vec4A); +outVec4 = vec4.negate(outVec4, vec4A); +outVec4 = vec4.inverse(outVec4, vec4A); +outVec4 = vec4.normalize(outVec4, vec4A); +outVal = vec4.dot(vec4A, vec4B); +outVec4 = vec4.lerp(outVec4, vec4A, vec4B, 0.5); +outVec4 = vec4.random(outVec4); +outVec4 = vec4.random(outVec4, 5.0); +outVec4 = vec4.transformMat4(outVec4, vec4A, mat4A); +outVec4 = vec4.transformQuat(outVec4, vec4A, quatA); +vecArray = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); +outStr = vec4.str(vec4A); +outBool = vec4.exactEquals(vec4A, vec4B); +outBool = vec4.equals(vec4A, vec4B); +outVec4 = vec4.add(outVec4, [0, 1, 2, 3], [4, 5, 6, 7]); // test one method with number array input // mat2 -var matB: GLM.IArray, identity: GLM.IArray; - -matA = [1, 2, 3, 4]; -matB = new Float32Array([5, 6, 7, 8]); -out = [0, 0, 0, 0]; -identity = [1, 0, 0, 1]; - -out = mat2.create(); -out = mat2.clone(matA); -out = mat2.copy(out, matA); -out = mat2.identity(out); -out = mat2.transpose(out, matA); -out = mat2.invert(out, matA); -out = mat2.adjoint(out, matA); -outVal = mat2.determinant(matA); -out = mat2.multiply(out, matA, matB); -out = mat2.mul(out, matA, matB); -out = mat2.rotate(out, matA, Math.PI * 0.5); - -vecA = [2, 3]; -out = mat2.scale(out, matA, vecA); -outStr = mat2.str(matA); -outVal = mat2.frob(matA); - -var L = mat2.create(); -var D = mat2.create(); +outMat2 = mat2.create(); +outMat2 = mat2.clone(mat2A); +outMat2 = mat2.copy(outMat2, mat2A); +outMat2 = mat2.identity(outMat2); +outMat2 = mat2.fromValues(1, 2, 3, 4); +outMat2 = mat2.set(outMat2, 1, 2, 3, 4); +outMat2 = mat2.transpose(outMat2, mat2A); +outMat2 = mat2.invert(outMat2, mat2A); +outMat2 = mat2.adjoint(outMat2, mat2A); +outVal = mat2.determinant(mat2A); +outMat2 = mat2.multiply(outMat2, mat2A, mat2B); +outMat2 = mat2.mul(outMat2, mat2A, mat2B); +outMat2 = mat2.rotate(outMat2, mat2A, Math.PI * 0.5); +outMat2 = mat2.scale(outMat2, mat2A, vec2A); +outMat2 = mat2.fromRotation(outMat2, 0.5); +outMat2 = mat2.fromScaling(outMat2, vec2A); +outStr = mat2.str(mat2A); +outVal = mat2.frob(mat2A); +var L = mat2.create(); +var D = mat2.create(); var U = mat2.create(); -out = mat2.LDU(L, D, U, [4,3,6,3]); +outMat2 = mat2.LDU(L, D, U, mat2A); +outMat2 = mat2.add(outMat2, mat2A, mat2B); +outMat2 = mat2.subtract(outMat2, mat2A, mat2B); +outMat2 = mat2.sub(outMat2, mat2A, mat2B); +outBool = mat2.exactEquals(mat2A, mat2B); +outBool = mat2.equals(mat2A, mat2B); +outMat2 = mat2.multiplyScalar (outMat2, mat2A, 2); +outMat2 = mat2.multiplyScalarAndAdd (outMat2, mat2A, mat2B, 2); // mat2d -matA = [1, 2, 3, 4, 5, 6]; -matB = [7, 8, 9, 10, 11, 12]; -out = [0, 0, 0, 0, 0, 0]; -identity = [1, 0, 0, 1, 0, 0]; - -out = mat2d.create(); -out = mat2d.clone(matA); -out = mat2d.copy(out, matA); -out = mat2d.identity(out); -out = mat2d.invert(out, matA); -outVal = mat2d.determinant(matA); -out = mat2d.multiply(out, matA, matB); -out = mat2d.mul(out, matA, matB); -out = mat2d.rotate(out, matA, Math.PI * 0.5); - -vecA = [2, 3]; -out = mat2d.scale(out, matA, vecA); -out = mat2d.translate(out, matA, vecA); -outStr = mat2d.str(matA); -outVal = mat2d.frob(matA); +outMat2d = mat2d.create(); +outMat2d = mat2d.clone(mat2dA); +outMat2d = mat2d.copy(outMat2d, mat2dA); +outMat2d = mat2d.identity(outMat2d); +outMat2d = mat2d.fromValues(1, 2, 3, 4, 5, 6); +outMat2d = mat2d.set(outMat2d, 1, 2, 3, 4, 5, 6); +outMat2d = mat2d.invert(outMat2d, mat2dA); +outVal = mat2d.determinant(mat2dA); +outMat2d = mat2d.multiply(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.mul(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.rotate(outMat2d, mat2dA, Math.PI * 0.5); +outMat2d = mat2d.scale(outMat2d, mat2dA, vec2A); +outMat2d = mat2d.translate(outMat2d, mat2dA, vec2A); +outMat2d = mat2d.fromRotation(outMat2d, 0.5); +outMat2d = mat2d.fromScaling(outMat2d, vec2A); +outMat2d = mat2d.fromTranslation(outMat2d, vec2A); +outStr = mat2d.str(mat2dA); +outVal = mat2d.frob(mat2dA); +outMat2d = mat2d.add(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.subtract(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.sub(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.multiplyScalar (outMat2d, mat2dA, 2); +outMat2d = mat2d.multiplyScalarAndAdd (outMat2d, mat2dA, mat2dB, 2); +outBool = mat2d.exactEquals(mat2dA, mat2dB); +outBool = mat2d.equals(mat2dA, mat2dB); // mat3 -matA = [1, 0, 0, 0, 1, 0, 1, 2, 1]; -matB = [1, 0, 0, 0, 1, 0, 3, 4, 1]; -out = [0, 0, 0, 0, 0, 0, 0, 0, 0]; -identity = [1, 0, 0, 0, 1, 0, 0, 0, 1]; - -out = mat3.create(); -out = mat3.clone(matA); -out = mat3.copy(out, matA); -out = mat3.identity(out); -out = mat3.transpose(out, matA); -out = mat3.invert(out, matA); -out = mat3.adjoint(out, matA); -outVal = mat3.determinant(matA); -out = mat3.multiply(out, matA, matB); -out = mat3.mul(out, matA, matB); -outStr = mat3.str(matA); -outVal = mat3.frob(matA); - -matA = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]; -out = mat3.normalFromMat4(out, matA); - -q = [ 0, -0.7071067811865475, 0, 0.7071067811865475 ]; -out = mat3.fromQuat(out, q); - -out = mat3.normalFromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); -out = mat3.fromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); -out = mat3.scale(out, matA, [2,2]); -out = mat3.fromMat2d(out, [1, 2, 3, 4, 5, 6]); - -out = mat3.translate(out, matA, [1, 2, 3]); -out = mat3.rotate(out, matA, Math.PI/2); - -// mat4 -matA = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 1, 2, 3, 1]; - -matB = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 4, 5, 6, 1]; - -out = [0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0]; - -identity = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]; - -out = mat4.create(); -out = mat4.clone(matA); -out = mat4.copy(out, matA); -out = mat4.identity(out); -out = mat4.transpose(out, matA); -out = mat4.invert(out, matA); -out = mat4.adjoint(out, matA); -outVal = mat4.determinant(matA); -out = mat4.multiply(out, matA, matB); -out = mat4.mul(out, matA, matB); -out = mat4.translate(out, matA, [4, 5, 6]); -out = mat4.scale(out, matA, [4, 5, 6]); - -var rad = Math.PI * 0.5; -var axis = [1, 0, 0]; -out = mat4.rotate(out, matA, rad, axis); -out = mat4.rotateX(out, matA, rad); -out = mat4.rotateY(out, matA, rad); -out = mat4.rotateZ(out, matA, rad); - -out = mat4.frustum(out, -1, 1, -1, 1, -1, 1); - -var fovy = Math.PI * 0.5; -out = mat4.perspective(out, fovy, 1, 0, 1); -out = mat4.ortho(out, -1, 1, -1, 1, -1, 1); - -var eye = [0, 0, 1]; -var center = [0, 0, -1]; -var up = [0, 1, 0]; -out = mat4.lookAt(out, eye, center, up); - -outStr = mat4.str(matA); -outVal = mat4.frob(matA); - -q = [0, 0, 0, 1]; -out = mat4.fromRotationTranslation(out, q, [1, 2, 3]); -out = mat4.fromQuat(out, q); - -q = [0, 0, 0, 1]; -out = mat4.fromRotationTranslationScale(out, q, [1, 2, 3], [1, 2, 3]); -out = mat4.fromQuat(out, q); +outMat3 = mat3.create(); +outMat3 = mat3.fromMat4(outMat3, mat4A); +outMat3 = mat3.clone(mat3A); +outMat3 = mat3.copy(outMat3, mat3A); +outMat3 = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +outMat3 = mat3.set(outMat3, 1, 2, 3, 4, 5, 6, 7, 8, 9); +outMat3 = mat3.identity(outMat3); +outMat3 = mat3.transpose(outMat3, mat3A); +outMat3 = mat3.invert(outMat3, mat3A); +outMat3 = mat3.adjoint(outMat3, mat3A); +outVal = mat3.determinant(mat3A); +outMat3 = mat3.multiply(outMat3, mat3A, mat3B); +outMat3 = mat3.mul(outMat3, mat3A, mat3B); +outMat3 = mat3.translate(outMat3, mat3A, vec3A); +outMat3 = mat3.rotate(outMat3, mat3A, Math.PI/2); +outMat3 = mat3.scale(outMat3, mat3A, vec2A); +outMat3 = mat3.fromTranslation(outMat3, vec2A); +outMat3 = mat3.fromRotation(outMat3, Math.PI); +outMat3 = mat3.fromScaling(outMat3, vec2A); +outMat3 = mat3.fromMat2d(outMat3, mat2dA); +outMat3 = mat3.fromQuat(outMat3, quatA); +outMat3 = mat3.normalFromMat4(outMat3, mat4A); +outStr = mat3.str(mat3A); +outVal = mat3.frob(mat3A); +outMat3 = mat3.add(outMat3, mat3A, mat3B); +outMat3 = mat3.subtract(outMat3, mat3A, mat3B); +outMat3 = mat3.sub(outMat3, mat3A, mat3B); +outMat3 = mat3.multiplyScalar (outMat3, mat3A, 2); +outMat3 = mat3.multiplyScalarAndAdd (outMat3, mat3A, mat3B, 2); +outBool = mat3.exactEquals(mat3A, mat3B); +outBool = mat3.equals(mat3A, mat3B); +//mat4 +outMat4 = mat4.create(); +outMat4 = mat4.clone(mat4A); +outMat4 = mat4.copy(outMat4, mat4A); +outMat4 = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +outMat4 = mat4.set(outMat4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +outMat4 = mat4.identity(outMat4); +outMat4 = mat4.transpose(outMat4, mat4A); +outMat4 = mat4.invert(outMat4, mat4A); +outMat4 = mat4.adjoint(outMat4, mat4A); +outVal = mat4.determinant(mat4A); +outMat4 = mat4.multiply(outMat4, mat4A, mat4B); +outMat4 = mat4.mul(outMat4, mat4A, mat4B); +outMat4 = mat4.translate(outMat4, mat4A, vec3A); +outMat4 = mat4.scale(outMat4, mat4A, vec3A); +outMat4 = mat4.rotate(outMat4, mat4A, Math.PI, vec3A); +outMat4 = mat4.rotateX(outMat4, mat4A, Math.PI); +outMat4 = mat4.rotateY(outMat4, mat4A, Math.PI); +outMat4 = mat4.rotateZ(outMat4, mat4A, Math.PI); +outMat4 = mat4.fromTranslation(outMat4, vec3A); +outMat4 = mat4.fromRotation(outMat4, Math.PI, vec3A); +outMat4 = mat4.fromScaling(outMat4, vec3A); +outMat4 = mat4.fromXRotation(outMat4, Math.PI); +outMat4 = mat4.fromYRotation(outMat4, Math.PI); +outMat4 = mat4.fromZRotation(outMat4, Math.PI); +outMat4 = mat4.fromRotationTranslation(outMat4, quatA, vec3A); +outVec3 = mat4.getTranslation(outVec3, mat4A) +outQuat = mat4.getRotation(outQuat, mat4A) +outMat4 = mat4.fromRotationTranslationScale(outMat4, quatA, vec3A, vec3B); +outMat4 = mat4.fromRotationTranslationScaleOrigin(outMat4, quatA, vec3A, vec3B, vec3A); +outMat4 = mat4.fromQuat(outMat4, quatB); +outMat4 = mat4.frustum(outMat4, -1, 1, -1, 1, -1, 1); +outMat4 = mat4.perspective(outMat4, Math.PI, 1, 0, 1); +outMat4 = mat4.perspectiveFromFieldOfView(outMat4, {upDegrees:Math.PI, downDegrees:-Math.PI, leftDegrees:-Math.PI, rightDegrees:Math.PI}, 1, 0); +outMat4 = mat4.ortho(outMat4, -1, 1, -1, 1, -1, 1); +outMat4 = mat4.lookAt(outMat4, vec3A, vec3B, vec3A); +outStr = mat4.str(mat4A); +outVal = mat4.frob(mat4A); +outMat4 = mat4.add(outMat4, mat4A, mat4B); +outMat4 = mat4.subtract(outMat4, mat4A, mat4B); +outMat4 = mat4.sub(outMat4, mat4A, mat4B); +outMat4 = mat4.multiplyScalar (outMat4, mat4A, 2); +outMat4 = mat4.multiplyScalarAndAdd (outMat4, mat4A, mat4B, 2); +outBool = mat4.exactEquals(mat4A, mat4B); +outBool = mat4.equals(mat4A, mat4B); // quat -var quatA = [1, 2, 3, 4]; -var quatB = [5, 6, 7, 8]; -out = [0, 0, 0, 0]; -var vec = [1, 1, -1]; -var id = [0, 0, 0, 1]; var deg90 = Math.PI / 2; - -out = quat.create(); -out = quat.clone(quatA); -out = quat.fromValues(1, 2, 3, 4); -out = quat.copy(out, quatA); -out = quat.set(out, 1, 2, 3, 4); -out = quat.identity(out); -out = quat.setAxisAngle(out, [1, 0, 0], Math.PI * 0.5); -out = quat.add(out, quatA, quatB); -out = quat.multiply(out, quatA, quatB); -out = quat.mul(out, quatA, quatB); -out = quat.scale(out, quatA, 2); +outQuat = quat.create(); +outQuat = quat.clone(quatA); +outQuat = quat.fromValues(1, 2, 3, 4); +outQuat = quat.copy(outQuat, quatA); +outQuat = quat.set(outQuat, 1, 2, 3, 4); +outQuat = quat.identity(outQuat); +outQuat = quat.rotationTo(outQuat, vec3A, vec3B); +outQuat = quat.setAxes(outQuat, vec3A, vec3B, vec3A); +outQuat = quat.setAxisAngle(outQuat, vec3A, Math.PI * 0.5); +outVal = quat.getAxisAngle (outVec3, quatA); +outQuat = quat.add(outQuat, quatA, quatB); +outQuat = quat.multiply(outQuat, quatA, quatB); +outQuat = quat.mul(outQuat, quatA, quatB); +outQuat = quat.scale(outQuat, quatA, 2); outVal = quat.length(quatA); outVal = quat.len(quatA); outVal = quat.squaredLength(quatA); outVal = quat.sqrLen(quatA); -out = quat.normalize(out, quatA); -outVal = quat.dot(out, quatA, quatB); -out = quat.lerp(out, quatA, quatB, 0.5); -out = quat.slerp(out, quatA, quatB, 0.5); -out = quat.invert(out, quatA); -out = quat.conjugate(out, quatA); +outQuat = quat.normalize(outQuat, quatA); +outVal = quat.dot(quatA, quatB); +outQuat = quat.lerp(outQuat, quatA, quatB, 0.5); +outQuat = quat.slerp(outQuat, quatA, quatB, 0.5); +outQuat = quat.invert(outQuat, quatA); +outQuat = quat.conjugate(outQuat, quatA); outStr = quat.str(quatA); -out = quat.rotateX(out, id, deg90); -out = quat.rotateY(out, id, deg90); -out = quat.rotateZ(out, id, deg90); - -matr = [ 1, 0, 0, - 0, 0, -1, - 0, 1, 0 ]; -out = quat.fromMat3(out, matr); - -var view = [-1, 0, 0]; -up = [ 0, 1, 0]; -var right= [ 0, 0,-1]; -out = quat.setAxes([], view, right, up); - -out = quat.rotationTo(out, [0, 1, 0], [1, 0, 0]); -out = quat.calculateW(out, quatA); - +outQuat = quat.rotateX(outQuat, quatA, deg90); +outQuat = quat.rotateY(outQuat, quatA, deg90); +outQuat = quat.rotateZ(outQuat, quatA, deg90); +outQuat = quat.fromMat3(outQuat, mat3A); +outQuat = quat.calculateW(outQuat, quatA); +outBool = quat.exactEquals(quatA, quatB); +outBool = quat.equals(quatA, quatB); diff --git a/gl-matrix/gl-matrix-typed-tests.ts b/gl-matrix/gl-matrix-typed-tests.ts deleted file mode 100644 index 64f6beb7a4..0000000000 --- a/gl-matrix/gl-matrix-typed-tests.ts +++ /dev/null @@ -1,347 +0,0 @@ -/// - -// common -import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "./gl-matrix-typed"; - -var outVal: number; -var outBool: boolean; -var outStr: string; - -let vecArray = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); - -let vec2A = vec2.fromValues(1, 2); -let vec2B = vec2.fromValues(3, 4); -let vec3A = vec3.fromValues(1, 2, 3); -let vec3B = vec3.fromValues(3, 4, 5); -let vec4A = vec4.fromValues(1, 2, 3, 4); -let vec4B = vec4.fromValues(3, 4, 5, 6); -let mat2A = mat2.fromValues(1, 2, 3, 4); -let mat2B = mat2.fromValues(1, 2, 3, 4); -let mat2dA = mat2d.fromValues(1, 2, 3, 4, 5, 6); -let mat2dB = mat2d.fromValues(1, 2, 3, 4, 5, 6); -let mat3A = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); -let mat3B = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); -let mat4A = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); -let mat4B = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); -let quatA = quat.fromValues(1, 2, 3, 4); -let quatB = quat.fromValues(5, 6, 7, 8); - -let outVec2 = vec2.create(); -let outVec3 = vec3.create(); -let outVec4 = vec4.create(); -let outMat2 = mat2.create(); -let outMat2d = mat2d.create(); -let outMat3 = mat3.create(); -let outMat4 = mat4.create(); -let outQuat = quat.create(); - -// vec2 -outVec2 = vec2.create(); -outVec2 = vec2.clone(vec2A); -outVec2 = vec2.fromValues(1, 2); -outVec2 = vec2.copy(outVec2, vec2A); -outVec2 = vec2.set(outVec2, 1, 2); -outVec2 = vec2.add(outVec2, vec2A, vec2B); -outVec2 = vec2.subtract(outVec2, vec2A, vec2B); -outVec2 = vec2.sub(outVec2, vec2A, vec2B); -outVec2 = vec2.multiply(outVec2, vec2A, vec2B); -outVec2 = vec2.mul(outVec2, vec2A, vec2B); -outVec2 = vec2.divide(outVec2, vec2A, vec2B); -outVec2 = vec2.div(outVec2, vec2A, vec2B); -outVec2 = vec2.ceil(outVec2, vec2A); -outVec2 = vec2.floor(outVec2, vec2A); -outVec2 = vec2.min(outVec2, vec2A, vec2B); -outVec2 = vec2.max(outVec2, vec2A, vec2B); -outVec2 = vec2.round(outVec2, vec2A); -outVec2 = vec2.scale(outVec2, vec2A, 2); -outVec2 = vec2.scaleAndAdd(outVec2, vec2A, vec2B, 0.5); -outVal = vec2.distance(vec2A, vec2B); -outVal = vec2.dist(vec2A, vec2B); -outVal = vec2.squaredDistance(vec2A, vec2B); -outVal = vec2.sqrDist(vec2A, vec2B); -outVal = vec2.length(vec2A); -outVal = vec2.len(vec2A); -outVal = vec2.squaredLength(vec2A); -outVal = vec2.sqrLen(vec2A); -outVec2 = vec2.negate(outVec2, vec2A); -outVec2 = vec2.inverse(outVec2, vec2A); -outVec2 = vec2.normalize(outVec2, vec2A); -outVal = vec2.dot(vec2A, vec2B); -outVec2 = vec2.cross(outVec2, vec2A, vec2B); -outVec2 = vec2.lerp(outVec2, vec2A, vec2B, 0.5); -outVec2 = vec2.random(outVec2); -outVec2 = vec2.random(outVec2, 5.0); -outVec2 = vec2.transformMat2(outVec2, vec2A, mat2A); -outVec2 = vec2.transformMat2d(outVec2, vec2A, mat2dA); -outVec2 = vec2.transformMat3(outVec2, vec2A, mat3A); -outVec2 = vec2.transformMat4(outVec2, vec2A, mat4A); -vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); -outStr = vec2.str(vec2A); -outBool = vec2.exactEquals(vec2A, vec2B); -outBool = vec2.equals(vec2A, vec2B); -outVec2 = vec2.add(outVec2, [0, 1], [2, 3]); // test one method with number array input - -// vec3 -outVec3 = vec3.create(); -outVec3 = vec3.clone(vec3A); -outVec3 = vec3.fromValues(1, 2, 3); -outVec3 = vec3.copy(outVec3, vec3A); -outVec3 = vec3.set(outVec3, 1, 2, 3); -outVec3 = vec3.add(outVec3, vec3A, vec3B); -outVec3 = vec3.subtract(outVec3, vec3A, vec3B); -outVec3 = vec3.sub(outVec3, vec3A, vec3B); -outVec3 = vec3.multiply(outVec3, vec3A, vec3B); -outVec3 = vec3.mul(outVec3, vec3A, vec3B); -outVec3 = vec3.divide(outVec3, vec3A, vec3B); -outVec3 = vec3.div(outVec3, vec3A, vec3B); -outVec3 = vec3.ceil(outVec3, vec3A); -outVec3 = vec3.floor(outVec3, vec3A); -outVec3 = vec3.min(outVec3, vec3A, vec3B); -outVec3 = vec3.max(outVec3, vec3A, vec3B); -outVec3 = vec3.round(outVec3, vec3A); -outVec3 = vec3.scale(outVec3, vec3A, 2); -outVec3 = vec3.scaleAndAdd(outVec3, vec3A, vec3B, 0.5); -outVal = vec3.distance(vec3A, vec3B); -outVal = vec3.dist(vec3A, vec3B); -outVal = vec3.squaredDistance(vec3A, vec3B); -outVal = vec3.sqrDist(vec3A, vec3B); -outVal = vec3.length(vec3A); -outVal = vec3.len(vec3A); -outVal = vec3.squaredLength(vec3A); -outVal = vec3.sqrLen(vec3A); -outVec3 = vec3.negate(outVec3, vec3A); -outVec3 = vec3.inverse(outVec3, vec3A); -outVec3 = vec3.normalize(outVec3, vec3A); -outVal = vec3.dot(vec3A, vec3B); -outVec3 = vec3.cross(outVec3, vec3A, vec3B); -outVec3 = vec3.lerp(outVec3, vec3A, vec3B, 0.5); -outVec3 = vec3.hermite(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); -outVec3 = vec3.bezier(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); -outVec3 = vec3.random(outVec3); -outVec3 = vec3.random(outVec3, 5.0); -outVec3 = vec3.transformMat3(outVec3, vec3A, mat3A); -outVec3 = vec3.transformMat4(outVec3, vec3A, mat4A); -outVec3 = vec3.transformQuat(outVec3, vec3A, quatA); -outVec3 = vec3.rotateX(outVec3, vec3A, vec3B, Math.PI); -outVec3 = vec3.rotateY(outVec3, vec3A, vec3B, Math.PI); -outVec3 = vec3.rotateZ(outVec3, vec3A, vec3B, Math.PI); -vecArray = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); -outVal = vec3.angle(vec3A, vec3B); -outStr = vec3.str(vec3A); -outBool = vec3.exactEquals(vec3A, vec3B); -outBool = vec3.equals(vec3A, vec3B); -outVec3 = vec3.add(outVec3, [0, 1, 2], [3, 4, 5]); // test one method with number array input - -// vec4 -outVec4 = vec4.create(); -outVec4 = vec4.clone(vec4A); -outVec4 = vec4.fromValues(1, 2, 3, 4); -outVec4 = vec4.copy(outVec4, vec4A); -outVec4 = vec4.set(outVec4, 1, 2, 3, 4); -outVec4 = vec4.add(outVec4, vec4A, vec4B); -outVec4 = vec4.subtract(outVec4, vec4A, vec4B); -outVec4 = vec4.sub(outVec4, vec4A, vec4B); -outVec4 = vec4.multiply(outVec4, vec4A, vec4B); -outVec4 = vec4.mul(outVec4, vec4A, vec4B); -outVec4 = vec4.divide(outVec4, vec4A, vec4B); -outVec4 = vec4.div(outVec4, vec4A, vec4B); -outVec4 = vec4.ceil(outVec4, vec4A); -outVec4 = vec4.floor(outVec4, vec4A); -outVec4 = vec4.min(outVec4, vec4A, vec4B); -outVec4 = vec4.max(outVec4, vec4A, vec4B); -outVec4 = vec4.scale(outVec4, vec4A, 2); -outVec4 = vec4.scaleAndAdd(outVec4, vec4A, vec4B, 0.5); -outVal = vec4.distance(vec4A, vec4B); -outVal = vec4.dist(vec4A, vec4B); -outVal = vec4.squaredDistance(vec4A, vec4B); -outVal = vec4.sqrDist(vec4A, vec4B); -outVal = vec4.length(vec4A); -outVal = vec4.len(vec4A); -outVal = vec4.squaredLength(vec4A); -outVal = vec4.sqrLen(vec4A); -outVec4 = vec4.negate(outVec4, vec4A); -outVec4 = vec4.inverse(outVec4, vec4A); -outVec4 = vec4.normalize(outVec4, vec4A); -outVal = vec4.dot(vec4A, vec4B); -outVec4 = vec4.lerp(outVec4, vec4A, vec4B, 0.5); -outVec4 = vec4.random(outVec4); -outVec4 = vec4.random(outVec4, 5.0); -outVec4 = vec4.transformMat4(outVec4, vec4A, mat4A); -outVec4 = vec4.transformQuat(outVec4, vec4A, quatA); -vecArray = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); -outStr = vec4.str(vec4A); -outBool = vec4.exactEquals(vec4A, vec4B); -outBool = vec4.equals(vec4A, vec4B); -outVec4 = vec4.add(outVec4, [0, 1, 2, 3], [4, 5, 6, 7]); // test one method with number array input - -// mat2 -outMat2 = mat2.create(); -outMat2 = mat2.clone(mat2A); -outMat2 = mat2.copy(outMat2, mat2A); -outMat2 = mat2.identity(outMat2); -outMat2 = mat2.fromValues(1, 2, 3, 4); -outMat2 = mat2.set(outMat2, 1, 2, 3, 4); -outMat2 = mat2.transpose(outMat2, mat2A); -outMat2 = mat2.invert(outMat2, mat2A); -outMat2 = mat2.adjoint(outMat2, mat2A); -outVal = mat2.determinant(mat2A); -outMat2 = mat2.multiply(outMat2, mat2A, mat2B); -outMat2 = mat2.mul(outMat2, mat2A, mat2B); -outMat2 = mat2.rotate(outMat2, mat2A, Math.PI * 0.5); -outMat2 = mat2.scale(outMat2, mat2A, vec2A); -outMat2 = mat2.fromRotation(outMat2, 0.5); -outMat2 = mat2.fromScaling(outMat2, vec2A); -outStr = mat2.str(mat2A); -outVal = mat2.frob(mat2A); -var L = mat2.create(); -var D = mat2.create(); -var U = mat2.create(); -outMat2 = mat2.LDU(L, D, U, mat2A); -outMat2 = mat2.add(outMat2, mat2A, mat2B); -outMat2 = mat2.subtract(outMat2, mat2A, mat2B); -outMat2 = mat2.sub(outMat2, mat2A, mat2B); -outBool = mat2.exactEquals(mat2A, mat2B); -outBool = mat2.equals(mat2A, mat2B); -outMat2 = mat2.multiplyScalar (outMat2, mat2A, 2); -outMat2 = mat2.multiplyScalarAndAdd (outMat2, mat2A, mat2B, 2); - -// mat2d -outMat2d = mat2d.create(); -outMat2d = mat2d.clone(mat2dA); -outMat2d = mat2d.copy(outMat2d, mat2dA); -outMat2d = mat2d.identity(outMat2d); -outMat2d = mat2d.fromValues(1, 2, 3, 4, 5, 6); -outMat2d = mat2d.set(outMat2d, 1, 2, 3, 4, 5, 6); -outMat2d = mat2d.invert(outMat2d, mat2dA); -outVal = mat2d.determinant(mat2dA); -outMat2d = mat2d.multiply(outMat2d, mat2dA, mat2dB); -outMat2d = mat2d.mul(outMat2d, mat2dA, mat2dB); -outMat2d = mat2d.rotate(outMat2d, mat2dA, Math.PI * 0.5); -outMat2d = mat2d.scale(outMat2d, mat2dA, vec2A); -outMat2d = mat2d.translate(outMat2d, mat2dA, vec2A); -outMat2d = mat2d.fromRotation(outMat2d, 0.5); -outMat2d = mat2d.fromScaling(outMat2d, vec2A); -outMat2d = mat2d.fromTranslation(outMat2d, vec2A); -outStr = mat2d.str(mat2dA); -outVal = mat2d.frob(mat2dA); -outMat2d = mat2d.add(outMat2d, mat2dA, mat2dB); -outMat2d = mat2d.subtract(outMat2d, mat2dA, mat2dB); -outMat2d = mat2d.sub(outMat2d, mat2dA, mat2dB); -outMat2d = mat2d.multiplyScalar (outMat2d, mat2dA, 2); -outMat2d = mat2d.multiplyScalarAndAdd (outMat2d, mat2dA, mat2dB, 2); -outBool = mat2d.exactEquals(mat2dA, mat2dB); -outBool = mat2d.equals(mat2dA, mat2dB); - -// mat3 -outMat3 = mat3.create(); -outMat3 = mat3.fromMat4(outMat3, mat4A); -outMat3 = mat3.clone(mat3A); -outMat3 = mat3.copy(outMat3, mat3A); -outMat3 = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); -outMat3 = mat3.set(outMat3, 1, 2, 3, 4, 5, 6, 7, 8, 9); -outMat3 = mat3.identity(outMat3); -outMat3 = mat3.transpose(outMat3, mat3A); -outMat3 = mat3.invert(outMat3, mat3A); -outMat3 = mat3.adjoint(outMat3, mat3A); -outVal = mat3.determinant(mat3A); -outMat3 = mat3.multiply(outMat3, mat3A, mat3B); -outMat3 = mat3.mul(outMat3, mat3A, mat3B); -outMat3 = mat3.translate(outMat3, mat3A, vec3A); -outMat3 = mat3.rotate(outMat3, mat3A, Math.PI/2); -outMat3 = mat3.scale(outMat3, mat3A, vec2A); -outMat3 = mat3.fromTranslation(outMat3, vec2A); -outMat3 = mat3.fromRotation(outMat3, Math.PI); -outMat3 = mat3.fromScaling(outMat3, vec2A); -outMat3 = mat3.fromMat2d(outMat3, mat2dA); -outMat3 = mat3.fromQuat(outMat3, quatA); -outMat3 = mat3.normalFromMat4(outMat3, mat4A); -outStr = mat3.str(mat3A); -outVal = mat3.frob(mat3A); -outMat3 = mat3.add(outMat3, mat3A, mat3B); -outMat3 = mat3.subtract(outMat3, mat3A, mat3B); -outMat3 = mat3.sub(outMat3, mat3A, mat3B); -outMat3 = mat3.multiplyScalar (outMat3, mat3A, 2); -outMat3 = mat3.multiplyScalarAndAdd (outMat3, mat3A, mat3B, 2); -outBool = mat3.exactEquals(mat3A, mat3B); -outBool = mat3.equals(mat3A, mat3B); - -//mat4 -outMat4 = mat4.create(); -outMat4 = mat4.clone(mat4A); -outMat4 = mat4.copy(outMat4, mat4A); -outMat4 = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); -outMat4 = mat4.set(outMat4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); -outMat4 = mat4.identity(outMat4); -outMat4 = mat4.transpose(outMat4, mat4A); -outMat4 = mat4.invert(outMat4, mat4A); -outMat4 = mat4.adjoint(outMat4, mat4A); -outVal = mat4.determinant(mat4A); -outMat4 = mat4.multiply(outMat4, mat4A, mat4B); -outMat4 = mat4.mul(outMat4, mat4A, mat4B); -outMat4 = mat4.translate(outMat4, mat4A, vec3A); -outMat4 = mat4.scale(outMat4, mat4A, vec3A); -outMat4 = mat4.rotate(outMat4, mat4A, Math.PI, vec3A); -outMat4 = mat4.rotateX(outMat4, mat4A, Math.PI); -outMat4 = mat4.rotateY(outMat4, mat4A, Math.PI); -outMat4 = mat4.rotateZ(outMat4, mat4A, Math.PI); -outMat4 = mat4.fromTranslation(outMat4, vec3A); -outMat4 = mat4.fromRotation(outMat4, Math.PI, vec3A); -outMat4 = mat4.fromScaling(outMat4, vec3A); -outMat4 = mat4.fromXRotation(outMat4, Math.PI); -outMat4 = mat4.fromYRotation(outMat4, Math.PI); -outMat4 = mat4.fromZRotation(outMat4, Math.PI); -outMat4 = mat4.fromRotationTranslation(outMat4, quatA, vec3A); -outVec3 = mat4.getTranslation(outVec3, mat4A) -outQuat = mat4.getRotation(outQuat, mat4A) -outMat4 = mat4.fromRotationTranslationScale(outMat4, quatA, vec3A, vec3B); -outMat4 = mat4.fromRotationTranslationScaleOrigin(outMat4, quatA, vec3A, vec3B, vec3A); -outMat4 = mat4.fromQuat(outMat4, quatB); -outMat4 = mat4.frustum(outMat4, -1, 1, -1, 1, -1, 1); -outMat4 = mat4.perspective(outMat4, Math.PI, 1, 0, 1); -outMat4 = mat4.perspectiveFromFieldOfView(outMat4, {upDegrees:Math.PI, downDegrees:-Math.PI, leftDegrees:-Math.PI, rightDegrees:Math.PI}, 1, 0); -outMat4 = mat4.ortho(outMat4, -1, 1, -1, 1, -1, 1); -outMat4 = mat4.lookAt(outMat4, vec3A, vec3B, vec3A); -outStr = mat4.str(mat4A); -outVal = mat4.frob(mat4A); -outMat4 = mat4.add(outMat4, mat4A, mat4B); -outMat4 = mat4.subtract(outMat4, mat4A, mat4B); -outMat4 = mat4.sub(outMat4, mat4A, mat4B); -outMat4 = mat4.multiplyScalar (outMat4, mat4A, 2); -outMat4 = mat4.multiplyScalarAndAdd (outMat4, mat4A, mat4B, 2); -outBool = mat4.exactEquals(mat4A, mat4B); -outBool = mat4.equals(mat4A, mat4B); - -// quat -var deg90 = Math.PI / 2; -outQuat = quat.create(); -outQuat = quat.clone(quatA); -outQuat = quat.fromValues(1, 2, 3, 4); -outQuat = quat.copy(outQuat, quatA); -outQuat = quat.set(outQuat, 1, 2, 3, 4); -outQuat = quat.identity(outQuat); -outQuat = quat.rotationTo(outQuat, vec3A, vec3B); -outQuat = quat.setAxes(outQuat, vec3A, vec3B, vec3A); -outQuat = quat.setAxisAngle(outQuat, vec3A, Math.PI * 0.5); -outVal = quat.getAxisAngle (outVec3, quatA); -outQuat = quat.add(outQuat, quatA, quatB); -outQuat = quat.multiply(outQuat, quatA, quatB); -outQuat = quat.mul(outQuat, quatA, quatB); -outQuat = quat.scale(outQuat, quatA, 2); -outVal = quat.length(quatA); -outVal = quat.len(quatA); -outVal = quat.squaredLength(quatA); -outVal = quat.sqrLen(quatA); -outQuat = quat.normalize(outQuat, quatA); -outVal = quat.dot(quatA, quatB); -outQuat = quat.lerp(outQuat, quatA, quatB, 0.5); -outQuat = quat.slerp(outQuat, quatA, quatB, 0.5); -outQuat = quat.invert(outQuat, quatA); -outQuat = quat.conjugate(outQuat, quatA); -outStr = quat.str(quatA); -outQuat = quat.rotateX(outQuat, quatA, deg90); -outQuat = quat.rotateY(outQuat, quatA, deg90); -outQuat = quat.rotateZ(outQuat, quatA, deg90); -outQuat = quat.fromMat3(outQuat, mat3A); -outQuat = quat.calculateW(outQuat, quatA); -outBool = quat.exactEquals(quatA, quatB); -outBool = quat.equals(quatA, quatB); \ No newline at end of file diff --git a/gl-matrix/gl-matrix-typed.d.ts b/gl-matrix/gl-matrix-typed.d.ts deleted file mode 100644 index 2edbbd8bb5..0000000000 --- a/gl-matrix/gl-matrix-typed.d.ts +++ /dev/null @@ -1,3044 +0,0 @@ -// Type definitions for gl-matrix 2.2.2 -// Project: https://github.com/toji/gl-matrix -// Definitions by: Mattijs Kneppers , based on definitions by Tat -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// vec2 -export class vec2 extends Float32Array { - private typeVec2: number; - - /** - * Creates a new, empty vec2 - * - * @returns a new 2D vector - */ - public static create(): vec2; - - /** - * Creates a new vec2 initialized with values from an existing vector - * - * @param a a vector to clone - * @returns a new 2D vector - */ - public static clone(a: vec2 | number[]): vec2; - - /** - * Creates a new vec2 initialized with the given values - * - * @param x X component - * @param y Y component - * @returns a new 2D vector - */ - public static fromValues(x: number, y: number): vec2; - - /** - * Copy the values from one vec2 to another - * - * @param out the receiving vector - * @param a the source vector - * @returns out - */ - public static copy(out: vec2, a: vec2 | number[]): vec2; - - /** - * Set the components of a vec2 to the given values - * - * @param out the receiving vector - * @param x X component - * @param y Y component - * @returns out - */ - public static set(out: vec2, x: number, y: number): vec2; - - /** - * Adds two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static add(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static subtract(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static sub(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Multiplies two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Multiplies two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Divides two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static divide(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Divides two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static div(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Math.ceil the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to ceil - * @returns {vec2} out - */ - public static ceil(out: vec2, a: vec2 | number[]): vec2; - - /** - * Math.floor the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to floor - * @returns {vec2} out - */ - public static floor (out: vec2, a: vec2 | number[]): vec2; - - /** - * Returns the minimum of two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static min(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Returns the maximum of two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static max(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Math.round the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to round - * @returns {vec2} out - */ - public static round(out: vec2, a: vec2 | number[]): vec2; - - - /** - * Scales a vec2 by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - */ - public static scale(out: vec2, a: vec2 | number[], b: number): vec2; - - /** - * Adds two vec2's after scaling the second operand by a scalar value - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param scale the amount to scale b by before adding - * @returns out - */ - public static scaleAndAdd(out: vec2, a: vec2 | number[], b: vec2 | number[], scale: number): vec2; - - /** - * Calculates the euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static distance(a: vec2 | number[], b: vec2 | number[]): number; - - /** - * Calculates the euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static dist(a: vec2 | number[], b: vec2 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static squaredDistance(a: vec2 | number[], b: vec2 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static sqrDist(a: vec2 | number[], b: vec2 | number[]): number; - - /** - * Calculates the length of a vec2 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec2 | number[]): number; - - /** - * Calculates the length of a vec2 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec2 | number[]): number; - - /** - * Calculates the squared length of a vec2 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static squaredLength(a: vec2 | number[]): number; - - /** - * Calculates the squared length of a vec2 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static sqrLen(a: vec2 | number[]): number; - - /** - * Negates the components of a vec2 - * - * @param out the receiving vector - * @param a vector to negate - * @returns out - */ - public static negate(out: vec2, a: vec2 | number[]): vec2; - - /** - * Returns the inverse of the components of a vec2 - * - * @param out the receiving vector - * @param a vector to invert - * @returns out - */ - public static inverse(out: vec2, a: vec2 | number[]): vec2; - - /** - * Normalize a vec2 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec2, a: vec2 | number[]): vec2; - - /** - * Calculates the dot product of two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - */ - public static dot(a: vec2 | number[], b: vec2 | number[]): number; - - /** - * Computes the cross product of two vec2's - * Note that the cross product must by definition produce a 3D vector - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static cross(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Performs a linear interpolation between two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static lerp(out: vec2, a: vec2 | number[], b: vec2 | number[], t: number): vec2; - - /** - * Generates a random unit vector - * - * @param out the receiving vector - * @returns out - */ - public static random(out: vec2): vec2; - - /** - * Generates a random vector with the given scale - * - * @param out the receiving vector - * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned - * @returns out - */ - public static random(out: vec2, scale: number): vec2; - - /** - * Transforms the vec2 with a mat2 - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat2(out: vec2, a: vec2 | number[], m: mat2): vec2; - - /** - * Transforms the vec2 with a mat2d - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat2d(out: vec2, a: vec2 | number[], m: mat2d): vec2; - - /** - * Transforms the vec2 with a mat3 - * 3rd vector component is implicitly '1' - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat3(out: vec2, a: vec2 | number[], m: mat3): vec2; - - /** - * Transforms the vec2 with a mat4 - * 3rd vector component is implicitly '0' - * 4th vector component is implicitly '1' - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat4(out: vec2, a: vec2 | number[], m: mat4): vec2; - - /** - * Perform some operation over an array of vec2s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec2s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @param arg additional argument to pass to fn - * @returns a - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; - - /** - * Perform some operation over an array of vec2s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec2s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @returns a - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2 | number[], b: vec2 | number[]) => void): Float32Array; - - /** - * Returns a string representation of a vector - * - * @param a vector to represent as a string - * @returns string representation of the vector - */ - public static str(a: vec2 | number[]): string; - - /** - * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) - * - * @param {vec2} a The first vector. - * @param {vec2} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static exactEquals (a: vec2 | number[], b: vec2 | number[]): boolean; - - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec2} a The first vector. - * @param {vec2} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static equals (a: vec2 | number[], b: vec2 | number[]): boolean; -} - -// vec3 -export class vec3 extends Float32Array { - private typeVec3: number; - - /** - * Creates a new, empty vec3 - * - * @returns a new 3D vector - */ - public static create(): vec3; - - /** - * Creates a new vec3 initialized with values from an existing vector - * - * @param a vector to clone - * @returns a new 3D vector - */ - public static clone(a: vec3 | number[]): vec3; - - /** - * Creates a new vec3 initialized with the given values - * - * @param x X component - * @param y Y component - * @param z Z component - * @returns a new 3D vector - */ - public static fromValues(x: number, y: number, z: number): vec3; - - /** - * Copy the values from one vec3 to another - * - * @param out the receiving vector - * @param a the source vector - * @returns out - */ - public static copy(out: vec3, a: vec3 | number[]): vec3; - - /** - * Set the components of a vec3 to the given values - * - * @param out the receiving vector - * @param x X component - * @param y Y component - * @param z Z component - * @returns out - */ - public static set(out: vec3, x: number, y: number, z: number): vec3; - - /** - * Adds two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static add(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static subtract(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static sub(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3 - - /** - * Multiplies two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Multiplies two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Divides two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static divide(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Divides two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static div(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Math.ceil the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to ceil - * @returns {vec3} out - */ - public static ceil (out: vec3, a: vec3 | number[]): vec3; - - /** - * Math.floor the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to floor - * @returns {vec3} out - */ - public static floor (out: vec3, a: vec3 | number[]): vec3; - - /** - * Returns the minimum of two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static min(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Returns the maximum of two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static max(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Math.round the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to round - * @returns {vec3} out - */ - public static round (out: vec3, a: vec3 | number[]): vec3 - - /** - * Scales a vec3 by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - */ - public static scale(out: vec3, a: vec3 | number[], b: number): vec3; - - /** - * Adds two vec3's after scaling the second operand by a scalar value - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param scale the amount to scale b by before adding - * @returns out - */ - public static scaleAndAdd(out: vec3, a: vec3 | number[], b: vec3 | number[], scale: number): vec3; - - /** - * Calculates the euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static distance(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static dist(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static squaredDistance(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static sqrDist(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the length of a vec3 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec3 | number[]): number; - - /** - * Calculates the length of a vec3 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec3 | number[]): number; - - /** - * Calculates the squared length of a vec3 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static squaredLength(a: vec3 | number[]): number; - - /** - * Calculates the squared length of a vec3 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static sqrLen(a: vec3 | number[]): number; - - /** - * Negates the components of a vec3 - * - * @param out the receiving vector - * @param a vector to negate - * @returns out - */ - public static negate(out: vec3, a: vec3 | number[]): vec3; - - /** - * Returns the inverse of the components of a vec3 - * - * @param out the receiving vector - * @param a vector to invert - * @returns out - */ - public static inverse(out: vec3, a: vec3 | number[]): vec3; - - /** - * Normalize a vec3 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec3, a: vec3 | number[]): vec3; - - /** - * Calculates the dot product of two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - */ - public static dot(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Computes the cross product of two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static cross(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Performs a linear interpolation between two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static lerp(out: vec3, a: vec3 | number[], b: vec3 | number[], t: number): vec3; - - /** - * Performs a hermite interpolation with two control points - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @param {vec3} c the third operand - * @param {vec3} d the fourth operand - * @param {number} t interpolation amount between the two inputs - * @returns {vec3} out - */ - public static hermite (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; - - /** - * Performs a bezier interpolation with two control points - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @param {vec3} c the third operand - * @param {vec3} d the fourth operand - * @param {number} t interpolation amount between the two inputs - * @returns {vec3} out - */ - public static bezier (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; - - /** - * Generates a random unit vector - * - * @param out the receiving vector - * @returns out - */ - public static random(out: vec3): vec3; - - /** - * Generates a random vector with the given scale - * - * @param out the receiving vector - * @param [scale] Length of the resulting vector. If omitted, a unit vector will be returned - * @returns out - */ - public static random(out: vec3, scale: number): vec3; - - /** - * Transforms the vec3 with a mat3. - * - * @param out the receiving vector - * @param a the vector to transform - * @param m the 3x3 matrix to transform with - * @returns out - */ - public static transformMat3(out: vec3, a: vec3 | number[], m: mat3): vec3; - - /** - * Transforms the vec3 with a mat4. - * 4th vector component is implicitly '1' - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat4(out: vec3, a: vec3 | number[], m: mat4): vec3; - - /** - * Transforms the vec3 with a quat - * - * @param out the receiving vector - * @param a the vector to transform - * @param q quaternion to transform with - * @returns out - */ - public static transformQuat(out: vec3, a: vec3 | number[], q: quat): vec3; - - - /** - * Rotate a 3D vector around the x-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - public static rotateX(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; - - /** - * Rotate a 3D vector around the y-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - public static rotateY(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; - - /** - * Rotate a 3D vector around the z-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - public static rotateZ(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; - - /** - * Perform some operation over an array of vec3s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec3s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @param arg additional argument to pass to fn - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3 | number[], b: vec3 | number[], arg: any) => void, arg: any): Float32Array; - - /** - * Perform some operation over an array of vec3s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec3s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3 | number[], b: vec3 | number[]) => void): Float32Array; - - /** - * Get the angle between two 3D vectors - * @param a The first operand - * @param b The second operand - * @returns The angle in radians - */ - public static angle(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Returns a string representation of a vector - * - * @param a vector to represent as a string - * @returns string representation of the vector - */ - public static str(a: vec3 | number[]): string; - - /** - * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) - * - * @param {vec3} a The first vector. - * @param {vec3} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static exactEquals (a: vec3 | number[], b: vec3 | number[]): boolean - - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec3} a The first vector. - * @param {vec3} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static equals (a: vec3 | number[], b: vec3 | number[]): boolean -} - -// vec4 -export class vec4 extends Float32Array { - private typeVec3: number; - - /** - * Creates a new, empty vec4 - * - * @returns a new 4D vector - */ - public static create(): vec4; - - /** - * Creates a new vec4 initialized with values from an existing vector - * - * @param a vector to clone - * @returns a new 4D vector - */ - public static clone(a: vec4 | number[]): vec4; - - /** - * Creates a new vec4 initialized with the given values - * - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns a new 4D vector - */ - public static fromValues(x: number, y: number, z: number, w: number): vec4; - - /** - * Copy the values from one vec4 to another - * - * @param out the receiving vector - * @param a the source vector - * @returns out - */ - public static copy(out: vec4, a: vec4 | number[]): vec4; - - /** - * Set the components of a vec4 to the given values - * - * @param out the receiving vector - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns out - */ - public static set(out: vec4, x: number, y: number, z: number, w: number): vec4; - - /** - * Adds two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static add(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static subtract(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static sub(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Multiplies two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Multiplies two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Divides two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static divide(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Divides two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static div(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Math.ceil the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to ceil - * @returns {vec4} out - */ - public static ceil (out: vec4, a: vec4 | number[]): vec4; - - /** - * Math.floor the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to floor - * @returns {vec4} out - */ - public static floor (out: vec4, a: vec4 | number[]): vec4; - - /** - * Returns the minimum of two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static min(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Returns the maximum of two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static max(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Math.round the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to round - * @returns {vec4} out - */ - public static round (out: vec4, a: vec4 | number[]): vec4; - - /** - * Scales a vec4 by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - */ - public static scale(out: vec4, a: vec4 | number[], b: number): vec4; - - /** - * Adds two vec4's after scaling the second operand by a scalar value - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param scale the amount to scale b by before adding - * @returns out - */ - public static scaleAndAdd(out: vec4, a: vec4 | number[], b: vec4 | number[], scale: number): vec4; - - /** - * Calculates the euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static distance(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static dist(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static squaredDistance(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static sqrDist(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the length of a vec4 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec4 | number[]): number; - - /** - * Calculates the length of a vec4 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec4 | number[]): number; - - /** - * Calculates the squared length of a vec4 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static squaredLength(a: vec4 | number[]): number; - - /** - * Calculates the squared length of a vec4 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static sqrLen(a: vec4 | number[]): number; - - /** - * Negates the components of a vec4 - * - * @param out the receiving vector - * @param a vector to negate - * @returns out - */ - public static negate(out: vec4, a: vec4 | number[]): vec4; - - /** - * Returns the inverse of the components of a vec4 - * - * @param out the receiving vector - * @param a vector to invert - * @returns out - */ - public static inverse(out: vec4, a: vec4 | number[]): vec4; - - /** - * Normalize a vec4 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec4, a: vec4 | number[]): vec4; - - /** - * Calculates the dot product of two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - */ - public static dot(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Performs a linear interpolation between two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static lerp(out: vec4, a: vec4 | number[], b: vec4 | number[], t: number): vec4; - - /** - * Generates a random unit vector - * - * @param out the receiving vector - * @returns out - */ - public static random(out: vec4): vec4; - - /** - * Generates a random vector with the given scale - * - * @param out the receiving vector - * @param scale length of the resulting vector. If ommitted, a unit vector will be returned - * @returns out - */ - public static random(out: vec4, scale: number): vec4; - - /** - * Transforms the vec4 with a mat4. - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat4(out: vec4, a: vec4 | number[], m: mat4): vec4; - - /** - * Transforms the vec4 with a quat - * - * @param out the receiving vector - * @param a the vector to transform - * @param q quaternion to transform with - * @returns out - */ - - public static transformQuat(out: vec4, a: vec4 | number[], q: quat): vec4; - - /** - * Perform some operation over an array of vec4s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec4s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @param arg additional argument to pass to fn - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4 | number[], b: vec4 | number[], arg: any) => void, arg: any): Float32Array; - - /** - * Perform some operation over an array of vec4s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec4s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4 | number[], b: vec4 | number[]) => void): Float32Array; - - /** - * Returns a string representation of a vector - * - * @param a vector to represent as a string - * @returns string representation of the vector - */ - public static str(a: vec4 | number[]): string; - - /** - * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) - * - * @param {vec4} a The first vector. - * @param {vec4} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static exactEquals (a: vec4 | number[], b: vec4 | number[]): boolean; - - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec4} a The first vector. - * @param {vec4} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static equals (a: vec4 | number[], b: vec4 | number[]): boolean; -} - -// mat2 -export class mat2 extends Float32Array { - private typeMat2: number; - - /** - * Creates a new identity mat2 - * - * @returns a new 2x2 matrix - */ - public static create(): mat2; - - /** - * Creates a new mat2 initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 2x2 matrix - */ - public static clone(a: mat2): mat2; - - /** - * Copy the values from one mat2 to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat2, a: mat2): mat2; - - /** - * Set a mat2 to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat2): mat2; - - /** - * Create a new mat2 with the given values - * - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m10 Component in column 1, row 0 position (index 2) - * @param {number} m11 Component in column 1, row 1 position (index 3) - * @returns {mat2} out A new 2x2 matrix - */ - public static fromValues(m00: number, m01: number, m10: number, m11: number): mat2; - - /** - * Set the components of a mat2 to the given values - * - * @param {mat2} out the receiving matrix - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m10 Component in column 1, row 0 position (index 2) - * @param {number} m11 Component in column 1, row 1 position (index 3) - * @returns {mat2} out - */ - public static set(out: mat2, m00: number, m01: number, m10: number, m11: number): mat2; - - /** - * Transpose the values of a mat2 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static transpose(out: mat2, a: mat2): mat2; - - /** - * Inverts a mat2 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat2, a: mat2): mat2; - - /** - * Calculates the adjugate of a mat2 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static adjoint(out: mat2, a: mat2): mat2; - - /** - * Calculates the determinant of a mat2 - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat2): number; - - /** - * Multiplies two mat2's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat2, a: mat2, b: mat2): mat2; - - /** - * Multiplies two mat2's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat2, a: mat2, b: mat2): mat2; - - /** - * Rotates a mat2 by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotate(out: mat2, a: mat2, rad: number): mat2; - - /** - * Scales the mat2 by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - public static scale(out: mat2, a: mat2, v: vec2 | number[]): mat2; - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat2.identity(dest); - * mat2.rotate(dest, dest, rad); - * - * @param {mat2} out mat2 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat2} out - */ - public static fromRotation(out: mat2, rad: number): mat2; - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat2.identity(dest); - * mat2.scale(dest, dest, vec); - * - * @param {mat2} out mat2 receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat2} out - */ - public static fromScaling(out: mat2, v: vec2 | number[]): mat2; - - /** - * Returns a string representation of a mat2 - * - * @param a matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(a: mat2): string; - - /** - * Returns Frobenius norm of a mat2 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat2): number; - - /** - * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix - * @param L the lower triangular matrix - * @param D the diagonal matrix - * @param U the upper triangular matrix - * @param a the input matrix to factorize - */ - public static LDU(L: mat2, D: mat2, U: mat2, a: mat2): mat2; - - /** - * Adds two mat2's - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - public static add(out: mat2, a: mat2, b: mat2): mat2; - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - public static subtract (out: mat2, a: mat2, b: mat2): mat2; - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - public static sub (out: mat2, a: mat2, b: mat2): mat2; - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat2} a The first matrix. - * @param {mat2} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals (a: mat2, b: mat2): boolean; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat2} a The first matrix. - * @param {mat2} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals (a: mat2, b: mat2): boolean; - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat2} out - */ - public static multiplyScalar (out: mat2, a: mat2, b: number): mat2 - - /** - * Adds two mat2's after multiplying each element of the second operand by a scalar value. - * - * @param {mat2} out the receiving vector - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat2} out - */ - public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale: number): mat2 - - - -} - -// mat2d -export class mat2d extends Float32Array { - private typeMat2d: number; - - /** - * Creates a new identity mat2d - * - * @returns a new 2x3 matrix - */ - public static create(): mat2d; - - /** - * Creates a new mat2d initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 2x3 matrix - */ - public static clone(a: mat2d): mat2d; - - /** - * Copy the values from one mat2d to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat2d, a: mat2d): mat2d; - - /** - * Set a mat2d to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat2d): mat2d; - - /** - * Create a new mat2d with the given values - * - * @param {number} a Component A (index 0) - * @param {number} b Component B (index 1) - * @param {number} c Component C (index 2) - * @param {number} d Component D (index 3) - * @param {number} tx Component TX (index 4) - * @param {number} ty Component TY (index 5) - * @returns {mat2d} A new mat2d - */ - public static fromValues (a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d - - - /** - * Set the components of a mat2d to the given values - * - * @param {mat2d} out the receiving matrix - * @param {number} a Component A (index 0) - * @param {number} b Component B (index 1) - * @param {number} c Component C (index 2) - * @param {number} d Component D (index 3) - * @param {number} tx Component TX (index 4) - * @param {number} ty Component TY (index 5) - * @returns {mat2d} out - */ - public static set (out: mat2d, a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d - - /** - * Inverts a mat2d - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat2d, a: mat2d): mat2d; - - /** - * Calculates the determinant of a mat2d - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat2d): number; - - /** - * Multiplies two mat2d's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat2d, a: mat2d, b: mat2d): mat2d; - - /** - * Multiplies two mat2d's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat2d, a: mat2d, b: mat2d): mat2d; - - /** - * Rotates a mat2d by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotate(out: mat2d, a: mat2d, rad: number): mat2d; - - /** - * Scales the mat2d by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - public static scale(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; - - /** - * Translates the mat2d by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v the vec2 to translate the matrix by - * @returns out - **/ - public static translate(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat2d.identity(dest); - * mat2d.rotate(dest, dest, rad); - * - * @param {mat2d} out mat2d receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat2d} out - */ - public static fromRotation (out: mat2d, rad: number): mat2d; - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat2d.identity(dest); - * mat2d.scale(dest, dest, vec); - * - * @param {mat2d} out mat2d receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat2d} out - */ - public static fromScaling (out: mat2d, v: vec2 | number[]): mat2d; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat2d.identity(dest); - * mat2d.translate(dest, dest, vec); - * - * @param {mat2d} out mat2d receiving operation result - * @param {vec2} v Translation vector - * @returns {mat2d} out - */ - public static fromTranslation (out: mat2d, v: vec2 | number[]): mat2d - - /** - * Returns a string representation of a mat2d - * - * @param a matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(a: mat2d): string; - - /** - * Returns Frobenius norm of a mat2d - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat2d): number; - - /** - * Adds two mat2d's - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @returns {mat2d} out - */ - public static add (out: mat2d, a: mat2d, b: mat2d): mat2d - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @returns {mat2d} out - */ - public static subtract(out: mat2d, a: mat2d, b: mat2d): mat2d - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @returns {mat2d} out - */ - public static sub(out: mat2d, a: mat2d, b: mat2d): mat2d - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat2d} out - */ - public static multiplyScalar (out: mat2d, a: mat2d, b: number): mat2d; - - /** - * Adds two mat2d's after multiplying each element of the second operand by a scalar value. - * - * @param {mat2d} out the receiving vector - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat2d} out - */ - public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale: number): mat2d - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat2d} a The first matrix. - * @param {mat2d} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals (a: mat2d, b: mat2d): boolean; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat2d} a The first matrix. - * @param {mat2d} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals (a: mat2d, b: mat2d): boolean -} - -// mat3 -export class mat3 extends Float32Array { - private typeMat3: number; - - /** - * Creates a new identity mat3 - * - * @returns a new 3x3 matrix - */ - public static create(): mat3; - - /** - * Copies the upper-left 3x3 values into the given mat3. - * - * @param {mat3} out the receiving 3x3 matrix - * @param {mat4} a the source 4x4 matrix - * @returns {mat3} out - */ - public static fromMat4(out: mat3, a: mat4): mat3 - - /** - * Creates a new mat3 initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 3x3 matrix - */ - public static clone(a: mat3): mat3; - - /** - * Copy the values from one mat3 to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat3, a: mat3): mat3; - - /** - * Create a new mat3 with the given values - * - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m10 Component in column 1, row 0 position (index 3) - * @param {number} m11 Component in column 1, row 1 position (index 4) - * @param {number} m12 Component in column 1, row 2 position (index 5) - * @param {number} m20 Component in column 2, row 0 position (index 6) - * @param {number} m21 Component in column 2, row 1 position (index 7) - * @param {number} m22 Component in column 2, row 2 position (index 8) - * @returns {mat3} A new mat3 - */ - public static fromValues(m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3; - - - /** - * Set the components of a mat3 to the given values - * - * @param {mat3} out the receiving matrix - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m10 Component in column 1, row 0 position (index 3) - * @param {number} m11 Component in column 1, row 1 position (index 4) - * @param {number} m12 Component in column 1, row 2 position (index 5) - * @param {number} m20 Component in column 2, row 0 position (index 6) - * @param {number} m21 Component in column 2, row 1 position (index 7) - * @param {number} m22 Component in column 2, row 2 position (index 8) - * @returns {mat3} out - */ - public static set(out: mat3, m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3 - - /** - * Set a mat3 to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat3): mat3; - - /** - * Transpose the values of a mat3 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static transpose(out: mat3, a: mat3): mat3; - - /** - * Inverts a mat3 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat3, a: mat3): mat3; - - /** - * Calculates the adjugate of a mat3 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static adjoint(out: mat3, a: mat3): mat3; - - /** - * Calculates the determinant of a mat3 - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat3): number; - - /** - * Multiplies two mat3's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat3, a: mat3, b: mat3): mat3; - - /** - * Multiplies two mat3's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat3, a: mat3, b: mat3): mat3; - - - /** - * Translate a mat3 by the given vector - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v vector to translate by - * @returns out - */ - public static translate(out: mat3, a: mat3, v: vec3 | number[]): mat3; - - /** - * Rotates a mat3 by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotate(out: mat3, a: mat3, rad: number): mat3; - - /** - * Scales the mat3 by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - public static scale(out: mat3, a: mat3, v: vec2 | number[]): mat3; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.translate(dest, dest, vec); - * - * @param {mat3} out mat3 receiving operation result - * @param {vec2} v Translation vector - * @returns {mat3} out - */ - public static fromTranslation(out: mat3, v: vec2 | number[]): mat3 - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.rotate(dest, dest, rad); - * - * @param {mat3} out mat3 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat3} out - */ - public static fromRotation(out: mat3, rad: number): mat3 - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.scale(dest, dest, vec); - * - * @param {mat3} out mat3 receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat3} out - */ - public static fromScaling(out: mat3, v: vec2 | number[]): mat3 - - /** - * Copies the values from a mat2d into a mat3 - * - * @param out the receiving matrix - * @param {mat2d} a the matrix to copy - * @returns out - **/ - public static fromMat2d(out: mat3, a: mat2d): mat3; - - /** - * Calculates a 3x3 matrix from the given quaternion - * - * @param out mat3 receiving operation result - * @param q Quaternion to create matrix from - * - * @returns out - */ - public static fromQuat(out: mat3, q: quat): mat3; - - /** - * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix - * - * @param out mat3 receiving operation result - * @param a Mat4 to derive the normal matrix from - * - * @returns out - */ - public static normalFromMat4(out: mat3, a: mat4): mat3; - - /** - * Returns a string representation of a mat3 - * - * @param mat matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(mat: mat3): string; - - /** - * Returns Frobenius norm of a mat3 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat3): number; - - /** - * Adds two mat3's - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - public static add(out: mat3, a: mat3, b: mat3): mat3 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - public static subtract(out: mat3, a: mat3, b: mat3): mat3 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - public static sub(out: mat3, a: mat3, b: mat3): mat3 - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat3} out - */ - public static multiplyScalar(out: mat3, a: mat3, b: number): mat3 - - /** - * Adds two mat3's after multiplying each element of the second operand by a scalar value. - * - * @param {mat3} out the receiving vector - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat3} out - */ - public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale: number): mat3 - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat3} a The first matrix. - * @param {mat3} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals(a: mat3, b: mat3): boolean; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat3} a The first matrix. - * @param {mat3} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals(a: mat3, b: mat3): boolean -} - -// mat4 -export class mat4 extends Float32Array { - private typeMat4: number; - - /** - * Creates a new identity mat4 - * - * @returns a new 4x4 matrix - */ - public static create(): mat4; - - /** - * Creates a new mat4 initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 4x4 matrix - */ - public static clone(a: mat4): mat4; - - /** - * Copy the values from one mat4 to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat4, a: mat4): mat4; - - - /** - * Create a new mat4 with the given values - * - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m03 Component in column 0, row 3 position (index 3) - * @param {number} m10 Component in column 1, row 0 position (index 4) - * @param {number} m11 Component in column 1, row 1 position (index 5) - * @param {number} m12 Component in column 1, row 2 position (index 6) - * @param {number} m13 Component in column 1, row 3 position (index 7) - * @param {number} m20 Component in column 2, row 0 position (index 8) - * @param {number} m21 Component in column 2, row 1 position (index 9) - * @param {number} m22 Component in column 2, row 2 position (index 10) - * @param {number} m23 Component in column 2, row 3 position (index 11) - * @param {number} m30 Component in column 3, row 0 position (index 12) - * @param {number} m31 Component in column 3, row 1 position (index 13) - * @param {number} m32 Component in column 3, row 2 position (index 14) - * @param {number} m33 Component in column 3, row 3 position (index 15) - * @returns {mat4} A new mat4 - */ - public static fromValues(m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; - - /** - * Set the components of a mat4 to the given values - * - * @param {mat4} out the receiving matrix - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m03 Component in column 0, row 3 position (index 3) - * @param {number} m10 Component in column 1, row 0 position (index 4) - * @param {number} m11 Component in column 1, row 1 position (index 5) - * @param {number} m12 Component in column 1, row 2 position (index 6) - * @param {number} m13 Component in column 1, row 3 position (index 7) - * @param {number} m20 Component in column 2, row 0 position (index 8) - * @param {number} m21 Component in column 2, row 1 position (index 9) - * @param {number} m22 Component in column 2, row 2 position (index 10) - * @param {number} m23 Component in column 2, row 3 position (index 11) - * @param {number} m30 Component in column 3, row 0 position (index 12) - * @param {number} m31 Component in column 3, row 1 position (index 13) - * @param {number} m32 Component in column 3, row 2 position (index 14) - * @param {number} m33 Component in column 3, row 3 position (index 15) - * @returns {mat4} out - */ - public static set(out: mat4, m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; - - /** - * Set a mat4 to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat4): mat4; - - /** - * Transpose the values of a mat4 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static transpose(out: mat4, a: mat4): mat4; - - /** - * Inverts a mat4 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat4, a: mat4): mat4; - - /** - * Calculates the adjugate of a mat4 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static adjoint(out: mat4, a: mat4): mat4; - - /** - * Calculates the determinant of a mat4 - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat4): number; - - /** - * Multiplies two mat4's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat4, a: mat4, b: mat4): mat4; - - /** - * Multiplies two mat4's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat4, a: mat4, b: mat4): mat4; - - /** - * Translate a mat4 by the given vector - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v vector to translate by - * @returns out - */ - public static translate(out: mat4, a: mat4, v: vec3 | number[]): mat4; - - /** - * Scales the mat4 by the dimensions in the given vec3 - * - * @param out the receiving matrix - * @param a the matrix to scale - * @param v the vec3 to scale the matrix by - * @returns out - **/ - public static scale(out: mat4, a: mat4, v: vec3 | number[]): mat4; - - /** - * Rotates a mat4 by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @param axis the axis to rotate around - * @returns out - */ - public static rotate(out: mat4, a: mat4, rad: number, axis: vec3 | number[]): mat4; - - /** - * Rotates a matrix by the given angle around the X axis - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotateX(out: mat4, a: mat4, rad: number): mat4; - - /** - * Rotates a matrix by the given angle around the Y axis - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotateY(out: mat4, a: mat4, rad: number): mat4; - - /** - * Rotates a matrix by the given angle around the Z axis - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotateZ(out: mat4, a: mat4, rad: number): mat4; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, dest, vec); - * - * @param {mat4} out mat4 receiving operation result - * @param {vec3} v Translation vector - * @returns {mat4} out - */ - public static fromTranslation(out: mat4, v: vec3 | number[]): mat4 - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.scale(dest, dest, vec); - * - * @param {mat4} out mat4 receiving operation result - * @param {vec3} v Scaling vector - * @returns {mat4} out - */ - public static fromScaling(out: mat4, v: vec3 | number[]): mat4 - - /** - * Creates a matrix from a given angle around a given axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotate(dest, dest, rad, axis); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @param {vec3} axis the axis to rotate around - * @returns {mat4} out - */ - public static fromRotation(out: mat4, rad: number, axis: vec3 | number[]): mat4 - - /** - * Creates a matrix from the given angle around the X axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateX(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - public static fromXRotation(out: mat4, rad: number): mat4 - - /** - * Creates a matrix from the given angle around the Y axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateY(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - public static fromYRotation(out: mat4, rad: number): mat4 - - - /** - * Creates a matrix from the given angle around the Z axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateZ(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - public static fromZRotation(out: mat4, rad: number): mat4 - - /** - * Creates a matrix from a quaternion rotation and vector translation - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * - * @param out mat4 receiving operation result - * @param q Rotation quaternion - * @param v Translation vector - * @returns out - */ - public static fromRotationTranslation(out: mat4, q: quat, v: vec3 | number[]): mat4; - - /** - * Returns the translation vector component of a transformation - * matrix. If a matrix is built with fromRotationTranslation, - * the returned vector will be the same as the translation vector - * originally supplied. - * @param {vec3} out Vector to receive translation component - * @param {mat4} mat Matrix to be decomposed (input) - * @return {vec3} out - */ - public static getTranslation(out: vec3, mat: mat4): vec3; - - /** - * Returns a quaternion representing the rotational component - * of a transformation matrix. If a matrix is built with - * fromRotationTranslation, the returned quaternion will be the - * same as the quaternion originally supplied. - * @param {quat} out Quaternion to receive the rotation component - * @param {mat4} mat Matrix to be decomposed (input) - * @return {quat} out - */ - public static getRotation(out: quat, mat: mat4): quat; - - /** - * Creates a matrix from a quaternion rotation, vector translation and vector scale - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * mat4.scale(dest, scale) - * - * @param out mat4 receiving operation result - * @param q Rotation quaternion - * @param v Translation vector - * @param s Scaling vector - * @returns out - */ - public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[]): mat4; - - /** - * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * mat4.translate(dest, origin); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * mat4.scale(dest, scale) - * mat4.translate(dest, negativeOrigin); - * - * @param {mat4} out mat4 receiving operation result - * @param {quat} q Rotation quaternion - * @param {vec3} v Translation vector - * @param {vec3} s Scaling vector - * @param {vec3} o The origin vector around which to scale and rotate - * @returns {mat4} out - */ - public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[], o: vec3 | number[]): mat4 - - /** - * Calculates a 4x4 matrix from the given quaternion - * - * @param {mat4} out mat4 receiving operation result - * @param {quat} q Quaternion to create matrix from - * - * @returns {mat4} out - */ - public static fromQuat(out: mat4, q: quat): mat4 - - /** - * Generates a frustum matrix with the given bounds - * - * @param out mat4 frustum matrix will be written into - * @param left Left bound of the frustum - * @param right Right bound of the frustum - * @param bottom Bottom bound of the frustum - * @param top Top bound of the frustum - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out - */ - public static frustum(out: mat4, left: number, right: number, - bottom: number, top: number, near: number, far: number): mat4; - - /** - * Generates a perspective projection matrix with the given bounds - * - * @param out mat4 frustum matrix will be written into - * @param fovy Vertical field of view in radians - * @param aspect Aspect ratio. typically viewport width/height - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out - */ - public static perspective(out: mat4, fovy: number, aspect: number, - near: number, far: number): mat4; - - /** - * Generates a perspective projection matrix with the given field of view. - * This is primarily useful for generating projection matrices to be used - * with the still experimental WebVR API. - * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees - * @param {number} near Near bound of the frustum - * @param {number} far Far bound of the frustum - * @returns {mat4} out - */ - public static perspectiveFromFieldOfView(out: mat4, - fov:{upDegrees: number, downDegrees: number, leftDegrees: number, rightDegrees: number}, - near: number, far: number): mat4 - - /** - * Generates a orthogonal projection matrix with the given bounds - * - * @param out mat4 frustum matrix will be written into - * @param left Left bound of the frustum - * @param right Right bound of the frustum - * @param bottom Bottom bound of the frustum - * @param top Top bound of the frustum - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out - */ - public static ortho(out: mat4, left: number, right: number, - bottom: number, top: number, near: number, far: number): mat4; - - /** - * Generates a look-at matrix with the given eye position, focal point, and up axis - * - * @param out mat4 frustum matrix will be written into - * @param eye Position of the viewer - * @param center Point the viewer is looking at - * @param up vec3 pointing up - * @returns out - */ - public static lookAt(out: mat4, eye: vec3 | number[], center: vec3 | number[], up: vec3 | number[]): mat4; - - /** - * Returns a string representation of a mat4 - * - * @param mat matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(mat: mat4): string; - - /** - * Returns Frobenius norm of a mat4 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat4): number; - - /** - * Adds two mat4's - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - public static add(out: mat4, a: mat4, b: mat4): mat4 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - public static subtract(out: mat4, a: mat4, b: mat4): mat4 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - public static sub(out: mat4, a: mat4, b: mat4): mat4 - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat4} out - */ - public static multiplyScalar(out: mat4, a: mat4, b: number): mat4 - - /** - * Adds two mat4's after multiplying each element of the second operand by a scalar value. - * - * @param {mat4} out the receiving vector - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat4} out - */ - public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale: number): mat4 - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat4} a The first matrix. - * @param {mat4} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals (a: mat4, b: mat4): boolean - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat4} a The first matrix. - * @param {mat4} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals (a: mat4, b: mat4): boolean - -} - -// quat -export class quat extends Float32Array { - private typeQuat: number; - - /** - * Creates a new identity quat - * - * @returns a new quaternion - */ - public static create(): quat; - - /** - * Creates a new quat initialized with values from an existing quaternion - * - * @param a quaternion to clone - * @returns a new quaternion - * @function - */ - public static clone(a: quat): quat; - - /** - * Creates a new quat initialized with the given values - * - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns a new quaternion - * @function - */ - public static fromValues(x: number, y: number, z: number, w: number): quat; - - /** - * Copy the values from one quat to another - * - * @param out the receiving quaternion - * @param a the source quaternion - * @returns out - * @function - */ - public static copy(out: quat, a: quat): quat; - - /** - * Set the components of a quat to the given values - * - * @param out the receiving quaternion - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns out - * @function - */ - public static set(out: quat, x: number, y: number, z: number, w: number): quat; - - /** - * Set a quat to the identity quaternion - * - * @param out the receiving quaternion - * @returns out - */ - public static identity(out: quat): quat; - - /** - * Sets a quaternion to represent the shortest rotation from one - * vector to another. - * - * Both vectors are assumed to be unit length. - * - * @param {quat} out the receiving quaternion. - * @param {vec3} a the initial vector - * @param {vec3} b the destination vector - * @returns {quat} out - */ - public static rotationTo (out: quat, a: vec3 | number[], b: vec3 | number[]): quat; - - /** - * Sets the specified quaternion with values corresponding to the given - * axes. Each axis is a vec3 and is expected to be unit length and - * perpendicular to all other specified axes. - * - * @param {vec3} view the vector representing the viewing direction - * @param {vec3} right the vector representing the local "right" direction - * @param {vec3} up the vector representing the local "up" direction - * @returns {quat} out - */ - public static setAxes (out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat - - - - /** - * Sets a quat from the given angle and rotation axis, - * then returns it. - * - * @param out the receiving quaternion - * @param axis the axis around which to rotate - * @param rad the angle in radians - * @returns out - **/ - public static setAxisAngle(out: quat, axis: vec3 | number[], rad: number): quat; - - /** - * Gets the rotation axis and angle for a given - * quaternion. If a quaternion is created with - * setAxisAngle, this method will return the same - * values as providied in the original parameter list - * OR functionally equivalent values. - * Example: The quaternion formed by axis [0, 0, 1] and - * angle -90 is the same as the quaternion formed by - * [0, 0, 1] and 270. This method favors the latter. - * @param {vec3} out_axis Vector receiving the axis of rotation - * @param {quat} q Quaternion to be decomposed - * @return {number} Angle, in radians, of the rotation - */ - public static getAxisAngle (out_axis: vec3 | number[], q: quat): number - - /** - * Adds two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @returns out - * @function - */ - public static add(out: quat, a: quat, b: quat): quat; - - /** - * Multiplies two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: quat, a: quat, b: quat): quat; - - /** - * Multiplies two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: quat, a: quat, b: quat): quat; - - /** - * Scales a quat by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - * @function - */ - public static scale(out: quat, a: quat, b: number): quat; - - /** - * Calculates the length of a quat - * - * @param a vector to calculate length of - * @returns length of a - * @function - */ - public static length(a: quat): number; - - /** - * Calculates the length of a quat - * - * @param a vector to calculate length of - * @returns length of a - * @function - */ - public static len(a: quat): number; - - /** - * Calculates the squared length of a quat - * - * @param a vector to calculate squared length of - * @returns squared length of a - * @function - */ - public static squaredLength(a: quat): number; - - /** - * Calculates the squared length of a quat - * - * @param a vector to calculate squared length of - * @returns squared length of a - * @function - */ - public static sqrLen(a: quat): number; - - /** - * Normalize a quat - * - * @param out the receiving quaternion - * @param a quaternion to normalize - * @returns out - * @function - */ - public static normalize(out: quat, a: quat): quat; - - /** - * Calculates the dot product of two quat's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - * @function - */ - public static dot(a: quat, b: quat): number; - - /** - * Performs a linear interpolation between two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - * @function - */ - public static lerp(out: quat, a: quat, b: quat, t: number): quat; - - /** - * Performs a spherical linear interpolation between two quat - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static slerp(out: quat, a: quat, b: quat, t: number): quat; - - /** - * Performs a spherical linear interpolation with two control points - * - * @param {quat} out the receiving quaternion - * @param {quat} a the first operand - * @param {quat} b the second operand - * @param {quat} c the third operand - * @param {quat} d the fourth operand - * @param {number} t interpolation amount - * @returns {quat} out - */ - public static sqlerp(out: quat, a: quat, b: quat, c: quat, d: quat, t: number): quat; - - /** - * Calculates the inverse of a quat - * - * @param out the receiving quaternion - * @param a quat to calculate inverse of - * @returns out - */ - public static invert(out: quat, a: quat): quat; - - /** - * Calculates the conjugate of a quat - * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. - * - * @param out the receiving quaternion - * @param a quat to calculate conjugate of - * @returns out - */ - public static conjugate(out: quat, a: quat): quat; - - /** - * Returns a string representation of a quaternion - * - * @param a quat to represent as a string - * @returns string representation of the quat - */ - public static str(a: quat): string; - - /** - * Rotates a quaternion by the given angle about the X axis - * - * @param out quat receiving operation result - * @param a quat to rotate - * @param rad angle (in radians) to rotate - * @returns out - */ - public static rotateX(out: quat, a: quat, rad: number): quat; - - /** - * Rotates a quaternion by the given angle about the Y axis - * - * @param out quat receiving operation result - * @param a quat to rotate - * @param rad angle (in radians) to rotate - * @returns out - */ - public static rotateY(out: quat, a: quat, rad: number): quat; - - /** - * Rotates a quaternion by the given angle about the Z axis - * - * @param out quat receiving operation result - * @param a quat to rotate - * @param rad angle (in radians) to rotate - * @returns out - */ - public static rotateZ(out: quat, a: quat, rad: number): quat; - - /** - * Creates a quaternion from the given 3x3 rotation matrix. - * - * NOTE: The resultant quaternion is not normalized, so you should be sure - * to renormalize the quaternion yourself where necessary. - * - * @param out the receiving quaternion - * @param m rotation matrix - * @returns out - * @function - */ - public static fromMat3(out: quat, m: mat3): quat; - - /** - * Sets the specified quaternion with values corresponding to the given - * axes. Each axis is a vec3 and is expected to be unit length and - * perpendicular to all other specified axes. - * - * @param out the receiving quat - * @param view the vector representing the viewing direction - * @param right the vector representing the local "right" direction - * @param up the vector representing the local "up" direction - * @returns out - */ - public static setAxes(out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat; - - /** - * Sets a quaternion to represent the shortest rotation from one - * vector to another. - * - * Both vectors are assumed to be unit length. - * - * @param out the receiving quaternion. - * @param a the initial vector - * @param b the destination vector - * @returns out - */ - public static rotationTo(out: quat, a: vec3 | number[], b: vec3 | number[]): quat; - - /** - * Calculates the W component of a quat from the X, Y, and Z components. - * Assumes that quaternion is 1 unit in length. - * Any existing W component will be ignored. - * - * @param out the receiving quaternion - * @param a quat to calculate W component of - * @returns out - */ - public static calculateW(out: quat, a: quat): quat; - - /** - * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) - * - * @param {quat} a The first vector. - * @param {quat} b The second vector. - * @returns {boolean} True if the quaternions are equal, false otherwise. - */ - public static exactEquals (a: quat, b: quat): boolean; - - /** - * Returns whether or not the quaternions have approximately the same elements in the same position. - * - * @param {quat} a The first vector. - * @param {quat} b The second vector. - * @returns {boolean} True if the quaternions are equal, false otherwise. - */ - public static equals (a: quat, b: quat): boolean; -} diff --git a/gl-matrix/gl-matrix.d.ts b/gl-matrix/gl-matrix.d.ts index 16366f263a..2edbbd8bb5 100644 --- a/gl-matrix/gl-matrix.d.ts +++ b/gl-matrix/gl-matrix.d.ts @@ -1,36 +1,18 @@ // Type definitions for gl-matrix 2.2.2 // Project: https://github.com/toji/gl-matrix -// Definitions by: Tat +// Definitions by: Mattijs Kneppers , based on definitions by Tat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace GLM { - interface IArray - { - /** - * Must be indexable like an array - */ - [index: number]: number; - } -} - -// Common -declare namespace glMatrix { - /** - * Convert Degree To Radian - * - * @param a Angle in Degrees - */ - export function toRadian(a: number): number; -} - // vec2 -declare namespace vec2 { +export class vec2 extends Float32Array { + private typeVec2: number; + /** * Creates a new, empty vec2 * * @returns a new 2D vector */ - export function create(): GLM.IArray; + public static create(): vec2; /** * Creates a new vec2 initialized with values from an existing vector @@ -38,7 +20,7 @@ declare namespace vec2 { * @param a a vector to clone * @returns a new 2D vector */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: vec2 | number[]): vec2; /** * Creates a new vec2 initialized with the given values @@ -47,7 +29,7 @@ declare namespace vec2 { * @param y Y component * @returns a new 2D vector */ - export function fromValues(x: number, y: number): GLM.IArray; + public static fromValues(x: number, y: number): vec2; /** * Copy the values from one vec2 to another @@ -56,7 +38,7 @@ declare namespace vec2 { * @param a the source vector * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: vec2, a: vec2 | number[]): vec2; /** * Set the components of a vec2 to the given values @@ -66,7 +48,7 @@ declare namespace vec2 { * @param y Y component * @returns out */ - export function set(out: GLM.IArray, x: number, y: number): GLM.IArray; + public static set(out: vec2, x: number, y: number): vec2; /** * Adds two vec2's @@ -76,7 +58,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Subtracts vector b from vector a @@ -86,7 +68,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static subtract(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Subtracts vector b from vector a @@ -96,7 +78,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static sub(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Multiplies two vec2's @@ -106,7 +88,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Multiplies two vec2's @@ -116,7 +98,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Divides two vec2's @@ -126,7 +108,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static divide(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Divides two vec2's @@ -136,7 +118,25 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static div(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + + /** + * Math.ceil the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to ceil + * @returns {vec2} out + */ + public static ceil(out: vec2, a: vec2 | number[]): vec2; + + /** + * Math.floor the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to floor + * @returns {vec2} out + */ + public static floor (out: vec2, a: vec2 | number[]): vec2; /** * Returns the minimum of two vec2's @@ -146,7 +146,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static min(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Returns the maximum of two vec2's @@ -156,7 +156,17 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static max(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + + /** + * Math.round the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to round + * @returns {vec2} out + */ + public static round(out: vec2, a: vec2 | number[]): vec2; + /** * Scales a vec2 by a scalar number @@ -166,7 +176,7 @@ declare namespace vec2 { * @param b amount to scale the vector by * @returns out */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: vec2, a: vec2 | number[], b: number): vec2; /** * Adds two vec2's after scaling the second operand by a scalar value @@ -177,7 +187,7 @@ declare namespace vec2 { * @param scale the amount to scale b by before adding * @returns out */ - export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + public static scaleAndAdd(out: vec2, a: vec2 | number[], b: vec2 | number[], scale: number): vec2; /** * Calculates the euclidian distance between two vec2's @@ -186,7 +196,7 @@ declare namespace vec2 { * @param b the second operand * @returns distance between a and b */ - export function distance(a: GLM.IArray, b: GLM.IArray): number; + public static distance(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the euclidian distance between two vec2's @@ -195,7 +205,7 @@ declare namespace vec2 { * @param b the second operand * @returns distance between a and b */ - export function dist(a: GLM.IArray, b: GLM.IArray): number; + public static dist(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the squared euclidian distance between two vec2's @@ -204,7 +214,7 @@ declare namespace vec2 { * @param b the second operand * @returns squared distance between a and b */ - export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + public static squaredDistance(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the squared euclidian distance between two vec2's @@ -213,7 +223,7 @@ declare namespace vec2 { * @param b the second operand * @returns squared distance between a and b */ - export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + public static sqrDist(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the length of a vec2 @@ -221,7 +231,7 @@ declare namespace vec2 { * @param a vector to calculate length of * @returns length of a */ - export function length(a: GLM.IArray): number; + public static length(a: vec2 | number[]): number; /** * Calculates the length of a vec2 @@ -229,7 +239,7 @@ declare namespace vec2 { * @param a vector to calculate length of * @returns length of a */ - export function len(a: GLM.IArray): number; + public static len(a: vec2 | number[]): number; /** * Calculates the squared length of a vec2 @@ -237,7 +247,7 @@ declare namespace vec2 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: vec2 | number[]): number; /** * Calculates the squared length of a vec2 @@ -245,7 +255,7 @@ declare namespace vec2 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: vec2 | number[]): number; /** * Negates the components of a vec2 @@ -254,7 +264,7 @@ declare namespace vec2 { * @param a vector to negate * @returns out */ - export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static negate(out: vec2, a: vec2 | number[]): vec2; /** * Returns the inverse of the components of a vec2 @@ -263,7 +273,7 @@ declare namespace vec2 { * @param a vector to invert * @returns out */ - export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static inverse(out: vec2, a: vec2 | number[]): vec2; /** * Normalize a vec2 @@ -272,7 +282,7 @@ declare namespace vec2 { * @param a vector to normalize * @returns out */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: vec2, a: vec2 | number[]): vec2; /** * Calculates the dot product of two vec2's @@ -281,7 +291,7 @@ declare namespace vec2 { * @param b the second operand * @returns dot product of a and b */ - export function dot(a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: vec2 | number[], b: vec2 | number[]): number; /** * Computes the cross product of two vec2's @@ -292,7 +302,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static cross(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Performs a linear interpolation between two vec2's @@ -303,7 +313,7 @@ declare namespace vec2 { * @param t interpolation amount between the two inputs * @returns out */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: vec2, a: vec2 | number[], b: vec2 | number[], t: number): vec2; /** * Generates a random unit vector @@ -311,7 +321,7 @@ declare namespace vec2 { * @param out the receiving vector * @returns out */ - export function random(out: GLM.IArray): GLM.IArray; + public static random(out: vec2): vec2; /** * Generates a random vector with the given scale @@ -320,7 +330,7 @@ declare namespace vec2 { * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned * @returns out */ - export function random(out: GLM.IArray, scale: number): GLM.IArray; + public static random(out: vec2, scale: number): vec2; /** * Transforms the vec2 with a mat2 @@ -330,7 +340,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat2(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat2(out: vec2, a: vec2 | number[], m: mat2): vec2; /** * Transforms the vec2 with a mat2d @@ -340,7 +350,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat2d(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat2d(out: vec2, a: vec2 | number[], m: mat2d): vec2; /** * Transforms the vec2 with a mat3 @@ -351,7 +361,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat3(out: vec2, a: vec2 | number[], m: mat3): vec2; /** * Transforms the vec2 with a mat4 @@ -363,7 +373,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat4(out: vec2, a: vec2 | number[], m: mat4): vec2; /** * Perform some operation over an array of vec2s. @@ -376,8 +386,8 @@ declare namespace vec2 { * @param arg additional argument to pass to fn * @returns a */ - export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec2s. @@ -389,27 +399,46 @@ declare namespace vec2 { * @param fn Function to call for each vector in the array * @returns a */ - export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2 | number[], b: vec2 | number[]) => void): Float32Array; /** * Returns a string representation of a vector * - * @param vec vector to represent as a string + * @param a vector to represent as a string * @returns string representation of the vector */ - export function str(a: GLM.IArray): string; + public static str(a: vec2 | number[]): string; + + /** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec2 | number[], b: vec2 | number[]): boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec2 | number[], b: vec2 | number[]): boolean; } // vec3 -declare namespace vec3 { +export class vec3 extends Float32Array { + private typeVec3: number; /** * Creates a new, empty vec3 * * @returns a new 3D vector */ - export function create(): GLM.IArray; + public static create(): vec3; /** * Creates a new vec3 initialized with values from an existing vector @@ -417,7 +446,7 @@ declare namespace vec3 { * @param a vector to clone * @returns a new 3D vector */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: vec3 | number[]): vec3; /** * Creates a new vec3 initialized with the given values @@ -427,7 +456,7 @@ declare namespace vec3 { * @param z Z component * @returns a new 3D vector */ - export function fromValues(x: number, y: number, z: number): GLM.IArray; + public static fromValues(x: number, y: number, z: number): vec3; /** * Copy the values from one vec3 to another @@ -436,7 +465,7 @@ declare namespace vec3 { * @param a the source vector * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: vec3, a: vec3 | number[]): vec3; /** * Set the components of a vec3 to the given values @@ -447,7 +476,7 @@ declare namespace vec3 { * @param z Z component * @returns out */ - export function set(out: GLM.IArray, x: number, y: number, z: number): GLM.IArray; + public static set(out: vec3, x: number, y: number, z: number): vec3; /** * Adds two vec3's @@ -457,7 +486,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Subtracts vector b from vector a @@ -467,7 +496,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static subtract(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Subtracts vector b from vector a @@ -477,7 +506,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray + public static sub(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3 /** * Multiplies two vec3's @@ -487,7 +516,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Multiplies two vec3's @@ -497,7 +526,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Divides two vec3's @@ -507,7 +536,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static divide(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Divides two vec3's @@ -517,7 +546,25 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static div(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Math.ceil the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to ceil + * @returns {vec3} out + */ + public static ceil (out: vec3, a: vec3 | number[]): vec3; + + /** + * Math.floor the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to floor + * @returns {vec3} out + */ + public static floor (out: vec3, a: vec3 | number[]): vec3; /** * Returns the minimum of two vec3's @@ -527,7 +574,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static min(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Returns the maximum of two vec3's @@ -537,7 +584,16 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static max(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Math.round the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to round + * @returns {vec3} out + */ + public static round (out: vec3, a: vec3 | number[]): vec3 /** * Scales a vec3 by a scalar number @@ -547,7 +603,7 @@ declare namespace vec3 { * @param b amount to scale the vector by * @returns out */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: vec3, a: vec3 | number[], b: number): vec3; /** * Adds two vec3's after scaling the second operand by a scalar value @@ -558,7 +614,7 @@ declare namespace vec3 { * @param scale the amount to scale b by before adding * @returns out */ - export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + public static scaleAndAdd(out: vec3, a: vec3 | number[], b: vec3 | number[], scale: number): vec3; /** * Calculates the euclidian distance between two vec3's @@ -567,7 +623,7 @@ declare namespace vec3 { * @param b the second operand * @returns distance between a and b */ - export function distance(a: GLM.IArray, b: GLM.IArray): number; + public static distance(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the euclidian distance between two vec3's @@ -576,7 +632,7 @@ declare namespace vec3 { * @param b the second operand * @returns distance between a and b */ - export function dist(a: GLM.IArray, b: GLM.IArray): number; + public static dist(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the squared euclidian distance between two vec3's @@ -585,7 +641,7 @@ declare namespace vec3 { * @param b the second operand * @returns squared distance between a and b */ - export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + public static squaredDistance(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the squared euclidian distance between two vec3's @@ -594,7 +650,7 @@ declare namespace vec3 { * @param b the second operand * @returns squared distance between a and b */ - export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + public static sqrDist(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the length of a vec3 @@ -602,7 +658,7 @@ declare namespace vec3 { * @param a vector to calculate length of * @returns length of a */ - export function length(a: GLM.IArray): number; + public static length(a: vec3 | number[]): number; /** * Calculates the length of a vec3 @@ -610,7 +666,7 @@ declare namespace vec3 { * @param a vector to calculate length of * @returns length of a */ - export function len(a: GLM.IArray): number; + public static len(a: vec3 | number[]): number; /** * Calculates the squared length of a vec3 @@ -618,7 +674,7 @@ declare namespace vec3 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: vec3 | number[]): number; /** * Calculates the squared length of a vec3 @@ -626,7 +682,7 @@ declare namespace vec3 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: vec3 | number[]): number; /** * Negates the components of a vec3 @@ -635,7 +691,7 @@ declare namespace vec3 { * @param a vector to negate * @returns out */ - export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static negate(out: vec3, a: vec3 | number[]): vec3; /** * Returns the inverse of the components of a vec3 @@ -644,7 +700,7 @@ declare namespace vec3 { * @param a vector to invert * @returns out */ - export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static inverse(out: vec3, a: vec3 | number[]): vec3; /** * Normalize a vec3 @@ -653,7 +709,7 @@ declare namespace vec3 { * @param a vector to normalize * @returns out */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: vec3, a: vec3 | number[]): vec3; /** * Calculates the dot product of two vec3's @@ -662,7 +718,7 @@ declare namespace vec3 { * @param b the second operand * @returns dot product of a and b */ - export function dot(a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: vec3 | number[], b: vec3 | number[]): number; /** * Computes the cross product of two vec3's @@ -672,7 +728,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static cross(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Performs a linear interpolation between two vec3's @@ -683,7 +739,33 @@ declare namespace vec3 { * @param t interpolation amount between the two inputs * @returns out */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: vec3, a: vec3 | number[], b: vec3 | number[], t: number): vec3; + + /** + * Performs a hermite interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + public static hermite (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; + + /** + * Performs a bezier interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + public static bezier (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; /** * Generates a random unit vector @@ -691,46 +773,16 @@ declare namespace vec3 { * @param out the receiving vector * @returns out */ - export function random(out: GLM.IArray): GLM.IArray; + public static random(out: vec3): vec3; /** * Generates a random vector with the given scale * * @param out the receiving vector - * @param [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @param [scale] Length of the resulting vector. If omitted, a unit vector will be returned * @returns out */ - export function random(out: GLM.IArray, scale: number): GLM.IArray; - - /** - * Rotate a 3D vector around the x-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - export function rotateX(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; - - /** - * Rotate a 3D vector around the y-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - export function rotateY(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; - - /** - * Rotate a 3D vector around the z-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - export function rotateZ(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + public static random(out: vec3, scale: number): vec3; /** * Transforms the vec3 with a mat3. @@ -740,7 +792,7 @@ declare namespace vec3 { * @param m the 3x3 matrix to transform with * @returns out */ - export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat3(out: vec3, a: vec3 | number[], m: mat3): vec3; /** * Transforms the vec3 with a mat4. @@ -751,9 +803,9 @@ declare namespace vec3 { * @param m matrix to transform with * @returns out */ - export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat4(out: vec3, a: vec3 | number[], m: mat4): vec3; - /** + /** * Transforms the vec3 with a quat * * @param out the receiving vector @@ -761,9 +813,39 @@ declare namespace vec3 { * @param q quaternion to transform with * @returns out */ - export function transformQuat(out: GLM.IArray, a: GLM.IArray, q: GLM.IArray): GLM.IArray; + public static transformQuat(out: vec3, a: vec3 | number[], q: quat): vec3; + /** + * Rotate a 3D vector around the x-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateX(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + + /** + * Rotate a 3D vector around the y-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateY(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + + /** + * Rotate a 3D vector around the z-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateZ(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + /** * Perform some operation over an array of vec3s. * @@ -776,8 +858,8 @@ declare namespace vec3 { * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3 | number[], b: vec3 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec3s. @@ -790,8 +872,8 @@ declare namespace vec3 { * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3 | number[], b: vec3 | number[]) => void): Float32Array; /** * Get the angle between two 3D vectors @@ -799,26 +881,45 @@ declare namespace vec3 { * @param b The second operand * @returns The angle in radians */ - export function angle(a: GLM.IArray, b: GLM.IArray): number; + public static angle(a: vec3 | number[], b: vec3 | number[]): number; /** * Returns a string representation of a vector * - * @param vec vector to represent as a string + * @param a vector to represent as a string * @returns string representation of the vector */ - export function str(a: GLM.IArray): string; + public static str(a: vec3 | number[]): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec3 | number[], b: vec3 | number[]): boolean + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec3 | number[], b: vec3 | number[]): boolean } // vec4 -declare namespace vec4 { +export class vec4 extends Float32Array { + private typeVec3: number; /** * Creates a new, empty vec4 * * @returns a new 4D vector */ - export function create(): GLM.IArray; + public static create(): vec4; /** * Creates a new vec4 initialized with values from an existing vector @@ -826,7 +927,7 @@ declare namespace vec4 { * @param a vector to clone * @returns a new 4D vector */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: vec4 | number[]): vec4; /** * Creates a new vec4 initialized with the given values @@ -837,7 +938,7 @@ declare namespace vec4 { * @param w W component * @returns a new 4D vector */ - export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + public static fromValues(x: number, y: number, z: number, w: number): vec4; /** * Copy the values from one vec4 to another @@ -846,7 +947,7 @@ declare namespace vec4 { * @param a the source vector * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: vec4, a: vec4 | number[]): vec4; /** * Set the components of a vec4 to the given values @@ -858,7 +959,7 @@ declare namespace vec4 { * @param w W component * @returns out */ - export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + public static set(out: vec4, x: number, y: number, z: number, w: number): vec4; /** * Adds two vec4's @@ -868,7 +969,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Subtracts vector b from vector a @@ -878,7 +979,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static subtract(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Subtracts vector b from vector a @@ -888,7 +989,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static sub(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Multiplies two vec4's @@ -898,7 +999,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Multiplies two vec4's @@ -908,7 +1009,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Divides two vec4's @@ -918,7 +1019,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static divide(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Divides two vec4's @@ -928,7 +1029,25 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static div(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Math.ceil the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to ceil + * @returns {vec4} out + */ + public static ceil (out: vec4, a: vec4 | number[]): vec4; + + /** + * Math.floor the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to floor + * @returns {vec4} out + */ + public static floor (out: vec4, a: vec4 | number[]): vec4; /** * Returns the minimum of two vec4's @@ -938,7 +1057,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static min(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Returns the maximum of two vec4's @@ -948,7 +1067,16 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static max(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Math.round the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to round + * @returns {vec4} out + */ + public static round (out: vec4, a: vec4 | number[]): vec4; /** * Scales a vec4 by a scalar number @@ -958,7 +1086,7 @@ declare namespace vec4 { * @param b amount to scale the vector by * @returns out */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: vec4, a: vec4 | number[], b: number): vec4; /** * Adds two vec4's after scaling the second operand by a scalar value @@ -969,7 +1097,7 @@ declare namespace vec4 { * @param scale the amount to scale b by before adding * @returns out */ - export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + public static scaleAndAdd(out: vec4, a: vec4 | number[], b: vec4 | number[], scale: number): vec4; /** * Calculates the euclidian distance between two vec4's @@ -978,7 +1106,7 @@ declare namespace vec4 { * @param b the second operand * @returns distance between a and b */ - export function distance(a: GLM.IArray, b: GLM.IArray): number; + public static distance(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the euclidian distance between two vec4's @@ -987,7 +1115,7 @@ declare namespace vec4 { * @param b the second operand * @returns distance between a and b */ - export function dist(a: GLM.IArray, b: GLM.IArray): number; + public static dist(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the squared euclidian distance between two vec4's @@ -996,7 +1124,7 @@ declare namespace vec4 { * @param b the second operand * @returns squared distance between a and b */ - export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + public static squaredDistance(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the squared euclidian distance between two vec4's @@ -1005,7 +1133,7 @@ declare namespace vec4 { * @param b the second operand * @returns squared distance between a and b */ - export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + public static sqrDist(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the length of a vec4 @@ -1013,7 +1141,7 @@ declare namespace vec4 { * @param a vector to calculate length of * @returns length of a */ - export function length(a: GLM.IArray): number; + public static length(a: vec4 | number[]): number; /** * Calculates the length of a vec4 @@ -1021,7 +1149,7 @@ declare namespace vec4 { * @param a vector to calculate length of * @returns length of a */ - export function len(a: GLM.IArray): number; + public static len(a: vec4 | number[]): number; /** * Calculates the squared length of a vec4 @@ -1029,7 +1157,7 @@ declare namespace vec4 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: vec4 | number[]): number; /** * Calculates the squared length of a vec4 @@ -1037,7 +1165,7 @@ declare namespace vec4 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: vec4 | number[]): number; /** * Negates the components of a vec4 @@ -1046,7 +1174,7 @@ declare namespace vec4 { * @param a vector to negate * @returns out */ - export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static negate(out: vec4, a: vec4 | number[]): vec4; /** * Returns the inverse of the components of a vec4 @@ -1055,7 +1183,7 @@ declare namespace vec4 { * @param a vector to invert * @returns out */ - export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static inverse(out: vec4, a: vec4 | number[]): vec4; /** * Normalize a vec4 @@ -1064,7 +1192,7 @@ declare namespace vec4 { * @param a vector to normalize * @returns out */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: vec4, a: vec4 | number[]): vec4; /** * Calculates the dot product of two vec4's @@ -1073,7 +1201,7 @@ declare namespace vec4 { * @param b the second operand * @returns dot product of a and b */ - export function dot(a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: vec4 | number[], b: vec4 | number[]): number; /** * Performs a linear interpolation between two vec4's @@ -1084,7 +1212,7 @@ declare namespace vec4 { * @param t interpolation amount between the two inputs * @returns out */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: vec4, a: vec4 | number[], b: vec4 | number[], t: number): vec4; /** * Generates a random unit vector @@ -1092,16 +1220,16 @@ declare namespace vec4 { * @param out the receiving vector * @returns out */ - export function random(out: GLM.IArray): GLM.IArray; + public static random(out: vec4): vec4; /** * Generates a random vector with the given scale * * @param out the receiving vector - * @param Length of the resulting vector. If ommitted, a unit vector will be returned + * @param scale length of the resulting vector. If ommitted, a unit vector will be returned * @returns out */ - export function random(out: GLM.IArray, scale: number): GLM.IArray; + public static random(out: vec4, scale: number): vec4; /** * Transforms the vec4 with a mat4. @@ -1111,7 +1239,7 @@ declare namespace vec4 { * @param m matrix to transform with * @returns out */ - export function transformMat4(out: GLM.IArray, a: GLM.IArray, mat: GLM.IArray): GLM.IArray; + public static transformMat4(out: vec4, a: vec4 | number[], m: mat4): vec4; /** * Transforms the vec4 with a quat @@ -1121,7 +1249,8 @@ declare namespace vec4 { * @param q quaternion to transform with * @returns out */ - export function transformQuat(out: GLM.IArray, a: GLM.IArray, quat: GLM.IArray): GLM.IArray; + + public static transformQuat(out: vec4, a: vec4 | number[], q: quat): vec4; /** * Perform some operation over an array of vec4s. @@ -1131,12 +1260,12 @@ declare namespace vec4 { * @param offset Number of elements to skip at the beginning of the array * @param count Number of vec4s to iterate over. If 0 iterates over entire array * @param fn Function to call for each vector in the array - * @param additional argument to pass to fn + * @param arg additional argument to pass to fn * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - callback: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4 | number[], b: vec4 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec4s. @@ -1149,27 +1278,46 @@ declare namespace vec4 { * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - callback: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4 | number[], b: vec4 | number[]) => void): Float32Array; /** * Returns a string representation of a vector * - * @param vec vector to represent as a string + * @param a vector to represent as a string * @returns string representation of the vector */ - export function str(a: GLM.IArray): string; + public static str(a: vec4 | number[]): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec4 | number[], b: vec4 | number[]): boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec4 | number[], b: vec4 | number[]): boolean; } // mat2 -declare namespace mat2 { +export class mat2 extends Float32Array { + private typeMat2: number; /** * Creates a new identity mat2 * * @returns a new 2x2 matrix */ - export function create(): GLM.IArray; + public static create(): mat2; /** * Creates a new mat2 initialized with values from an existing matrix @@ -1177,7 +1325,7 @@ declare namespace mat2 { * @param a matrix to clone * @returns a new 2x2 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat2): mat2; /** * Copy the values from one mat2 to another @@ -1186,7 +1334,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: mat2, a: mat2): mat2; /** * Set a mat2 to the identity matrix @@ -1194,7 +1342,30 @@ declare namespace mat2 { * @param out the receiving matrix * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + public static identity(out: mat2): mat2; + + /** + * Create a new mat2 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out A new 2x2 matrix + */ + public static fromValues(m00: number, m01: number, m10: number, m11: number): mat2; + + /** + * Set the components of a mat2 to the given values + * + * @param {mat2} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out + */ + public static set(out: mat2, m00: number, m01: number, m10: number, m11: number): mat2; /** * Transpose the values of a mat2 @@ -1203,7 +1374,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static transpose(out: mat2, a: mat2): mat2; /** * Inverts a mat2 @@ -1212,7 +1383,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat2, a: mat2): mat2; /** * Calculates the adjugate of a mat2 @@ -1221,7 +1392,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static adjoint(out: mat2, a: mat2): mat2; /** * Calculates the determinant of a mat2 @@ -1229,7 +1400,7 @@ declare namespace mat2 { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat2): number; /** * Multiplies two mat2's @@ -1239,7 +1410,7 @@ declare namespace mat2 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat2, a: mat2, b: mat2): mat2; /** * Multiplies two mat2's @@ -1249,7 +1420,7 @@ declare namespace mat2 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat2, a: mat2, b: mat2): mat2; /** * Rotates a mat2 by the given angle @@ -1259,7 +1430,7 @@ declare namespace mat2 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotate(out: mat2, a: mat2, rad: number): mat2; /** * Scales the mat2 by the dimensions in the given vec2 @@ -1269,7 +1440,33 @@ declare namespace mat2 { * @param v the vec2 to scale the matrix by * @returns out **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static scale(out: mat2, a: mat2, v: vec2 | number[]): mat2; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.rotate(dest, dest, rad); + * + * @param {mat2} out mat2 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + public static fromRotation(out: mat2, rad: number): mat2; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.scale(dest, dest, vec); + * + * @param {mat2} out mat2 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2} out + */ + public static fromScaling(out: mat2, v: vec2 | number[]): mat2; /** * Returns a string representation of a mat2 @@ -1277,7 +1474,7 @@ declare namespace mat2 { * @param a matrix to represent as a string * @returns string representation of the matrix */ - export function str(a: GLM.IArray): string; + public static str(a: mat2): string; /** * Returns Frobenius norm of a mat2 @@ -1285,7 +1482,7 @@ declare namespace mat2 { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - export function frob(a: GLM.IArray): number; + public static frob(a: mat2): number; /** * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix @@ -1294,18 +1491,91 @@ declare namespace mat2 { * @param U the upper triangular matrix * @param a the input matrix to factorize */ - export function LDU(L: GLM.IArray, D: GLM.IArray, U: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static LDU(L: mat2, D: mat2, U: mat2, a: mat2): mat2; + + /** + * Adds two mat2's + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static add(out: mat2, a: mat2, b: mat2): mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static subtract (out: mat2, a: mat2, b: mat2): mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static sub (out: mat2, a: mat2, b: mat2): mat2; + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat2, b: mat2): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat2, b: mat2): boolean; + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2} out + */ + public static multiplyScalar (out: mat2, a: mat2, b: number): mat2 + + /** + * Adds two mat2's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2} out the receiving vector + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2} out + */ + public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale: number): mat2 + + + } // mat2d -declare namespace mat2d { +export class mat2d extends Float32Array { + private typeMat2d: number; /** * Creates a new identity mat2d * * @returns a new 2x3 matrix */ - export function create(): GLM.IArray; + public static create(): mat2d; /** * Creates a new mat2d initialized with values from an existing matrix @@ -1313,7 +1583,7 @@ declare namespace mat2d { * @param a matrix to clone * @returns a new 2x3 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat2d): mat2d; /** * Copy the values from one mat2d to another @@ -1322,7 +1592,7 @@ declare namespace mat2d { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: mat2d, a: mat2d): mat2d; /** * Set a mat2d to the identity matrix @@ -1330,7 +1600,35 @@ declare namespace mat2d { * @param out the receiving matrix * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + public static identity(out: mat2d): mat2d; + + /** + * Create a new mat2d with the given values + * + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} A new mat2d + */ + public static fromValues (a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d + + + /** + * Set the components of a mat2d to the given values + * + * @param {mat2d} out the receiving matrix + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} out + */ + public static set (out: mat2d, a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d /** * Inverts a mat2d @@ -1339,7 +1637,7 @@ declare namespace mat2d { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat2d, a: mat2d): mat2d; /** * Calculates the determinant of a mat2d @@ -1347,7 +1645,7 @@ declare namespace mat2d { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat2d): number; /** * Multiplies two mat2d's @@ -1357,7 +1655,7 @@ declare namespace mat2d { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat2d, a: mat2d, b: mat2d): mat2d; /** * Multiplies two mat2d's @@ -1367,7 +1665,7 @@ declare namespace mat2d { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat2d, a: mat2d, b: mat2d): mat2d; /** * Rotates a mat2d by the given angle @@ -1377,7 +1675,7 @@ declare namespace mat2d { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotate(out: mat2d, a: mat2d, rad: number): mat2d; /** * Scales the mat2d by the dimensions in the given vec2 @@ -1387,7 +1685,7 @@ declare namespace mat2d { * @param v the vec2 to scale the matrix by * @returns out **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static scale(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; /** * Translates the mat2d by the dimensions in the given vec2 @@ -1397,7 +1695,46 @@ declare namespace mat2d { * @param v the vec2 to translate the matrix by * @returns out **/ - export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static translate(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.rotate(dest, dest, rad); + * + * @param {mat2d} out mat2d receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ + public static fromRotation (out: mat2d, rad: number): mat2d; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.scale(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2d} out + */ + public static fromScaling (out: mat2d, v: vec2 | number[]): mat2d; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.translate(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Translation vector + * @returns {mat2d} out + */ + public static fromTranslation (out: mat2d, v: vec2 | number[]): mat2d /** * Returns a string representation of a mat2d @@ -1405,7 +1742,7 @@ declare namespace mat2d { * @param a matrix to represent as a string * @returns string representation of the matrix */ - export function str(a: GLM.IArray): string; + public static str(a: mat2d): string; /** * Returns Frobenius norm of a mat2d @@ -1413,18 +1750,97 @@ declare namespace mat2d { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - export function frob(a: GLM.IArray): number; + public static frob(a: mat2d): number; + + /** + * Adds two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static add (out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static subtract(out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static sub(out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2d} out + */ + public static multiplyScalar (out: mat2d, a: mat2d, b: number): mat2d; + + /** + * Adds two mat2d's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2d} out the receiving vector + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2d} out + */ + public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale: number): mat2d + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat2d, b: mat2d): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat2d, b: mat2d): boolean } // mat3 -declare namespace mat3 { +export class mat3 extends Float32Array { + private typeMat3: number; /** * Creates a new identity mat3 * * @returns a new 3x3 matrix */ - export function create(): GLM.IArray; + public static create(): mat3; + + /** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param {mat3} out the receiving 3x3 matrix + * @param {mat4} a the source 4x4 matrix + * @returns {mat3} out + */ + public static fromMat4(out: mat3, a: mat4): mat3 /** * Creates a new mat3 initialized with values from an existing matrix @@ -1432,7 +1848,7 @@ declare namespace mat3 { * @param a matrix to clone * @returns a new 3x3 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat3): mat3; /** * Copy the values from one mat3 to another @@ -1441,7 +1857,41 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: mat3, a: mat3): mat3; + + /** + * Create a new mat3 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} A new mat3 + */ + public static fromValues(m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3; + + + /** + * Set the components of a mat3 to the given values + * + * @param {mat3} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} out + */ + public static set(out: mat3, m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3 /** * Set a mat3 to the identity matrix @@ -1449,7 +1899,7 @@ declare namespace mat3 { * @param out the receiving matrix * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + public static identity(out: mat3): mat3; /** * Transpose the values of a mat3 @@ -1458,7 +1908,7 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static transpose(out: mat3, a: mat3): mat3; /** * Inverts a mat3 @@ -1467,7 +1917,7 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat3, a: mat3): mat3; /** * Calculates the adjugate of a mat3 @@ -1476,7 +1926,7 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static adjoint(out: mat3, a: mat3): mat3; /** * Calculates the determinant of a mat3 @@ -1484,7 +1934,7 @@ declare namespace mat3 { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat3): number; /** * Multiplies two mat3's @@ -1494,7 +1944,7 @@ declare namespace mat3 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat3, a: mat3, b: mat3): mat3; /** * Multiplies two mat3's @@ -1504,71 +1954,8 @@ declare namespace mat3 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat3, a: mat3, b: mat3): mat3; - /** - * Returns a string representation of a mat3 - * - * @param mat matrix to represent as a string - * @returns string representation of the matrix - */ - export function str(mat: GLM.IArray): string; - - /** - * Returns Frobenius norm of a mat3 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - export function frob(a: GLM.IArray): number; - - /** - * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix - * - * @param out mat3 receiving operation result - * @param a Mat4 to derive the normal matrix from - * - * @returns out - */ - export function normalFromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; - - /** - * Calculates a 3x3 matrix from the given quaternion - * - * @param out mat3 receiving operation result - * @param q Quaternion to create matrix from - * - * @returns out - */ - export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; - - /** - * Copies the upper-left 3x3 values into the given mat3. - * - * @param out the receiving 3x3 matrix - * @param a the source 4x4 matrix - * @returns out - */ - export function fromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; - - /** - * Scales the mat3 by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; - - /** - * Copies the values from a mat2d into a mat3 - * - * @param out the receiving matrix - * @param {mat2d} a the matrix to copy - * @returns out - **/ - export function fromMat2d(out: GLM.IArray, a: GLM.IArray): GLM.IArray; /** * Translate a mat3 by the given vector @@ -1578,7 +1965,7 @@ declare namespace mat3 { * @param v vector to translate by * @returns out */ - export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static translate(out: mat3, a: mat3, v: vec3 | number[]): mat3; /** * Rotates a mat3 by the given angle @@ -1588,18 +1975,182 @@ declare namespace mat3 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotate(out: mat3, a: mat3, rad: number): mat3; + + /** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out: mat3, a: mat3, v: vec2 | number[]): mat3; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.translate(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Translation vector + * @returns {mat3} out + */ + public static fromTranslation(out: mat3, v: vec2 | number[]): mat3 + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.rotate(dest, dest, rad); + * + * @param {mat3} out mat3 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + public static fromRotation(out: mat3, rad: number): mat3 + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.scale(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat3} out + */ + public static fromScaling(out: mat3, v: vec2 | number[]): mat3 + + /** + * Copies the values from a mat2d into a mat3 + * + * @param out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns out + **/ + public static fromMat2d(out: mat3, a: mat2d): mat3; + + /** + * Calculates a 3x3 matrix from the given quaternion + * + * @param out mat3 receiving operation result + * @param q Quaternion to create matrix from + * + * @returns out + */ + public static fromQuat(out: mat3, q: quat): mat3; + + /** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param out mat3 receiving operation result + * @param a Mat4 to derive the normal matrix from + * + * @returns out + */ + public static normalFromMat4(out: mat3, a: mat4): mat3; + + /** + * Returns a string representation of a mat3 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(mat: mat3): string; + + /** + * Returns Frobenius norm of a mat3 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat3): number; + + /** + * Adds two mat3's + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static add(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static subtract(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static sub(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat3} out + */ + public static multiplyScalar(out: mat3, a: mat3, b: number): mat3 + + /** + * Adds two mat3's after multiplying each element of the second operand by a scalar value. + * + * @param {mat3} out the receiving vector + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat3} out + */ + public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale: number): mat3 + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals(a: mat3, b: mat3): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals(a: mat3, b: mat3): boolean } // mat4 -declare namespace mat4 { +export class mat4 extends Float32Array { + private typeMat4: number; /** * Creates a new identity mat4 * * @returns a new 4x4 matrix */ - export function create(): GLM.IArray; + public static create(): mat4; /** * Creates a new mat4 initialized with values from an existing matrix @@ -1607,7 +2158,7 @@ declare namespace mat4 { * @param a matrix to clone * @returns a new 4x4 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat4): mat4; /** * Copy the values from one mat4 to another @@ -1616,7 +2167,55 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: mat4, a: mat4): mat4; + + + /** + * Create a new mat4 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} A new mat4 + */ + public static fromValues(m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; + + /** + * Set the components of a mat4 to the given values + * + * @param {mat4} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} out + */ + public static set(out: mat4, m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; /** * Set a mat4 to the identity matrix @@ -1624,7 +2223,7 @@ declare namespace mat4 { * @param out the receiving matrix * @returns out */ - export function identity(a: GLM.IArray): GLM.IArray; + public static identity(out: mat4): mat4; /** * Transpose the values of a mat4 @@ -1633,7 +2232,7 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static transpose(out: mat4, a: mat4): mat4; /** * Inverts a mat4 @@ -1642,7 +2241,7 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat4, a: mat4): mat4; /** * Calculates the adjugate of a mat4 @@ -1651,7 +2250,7 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static adjoint(out: mat4, a: mat4): mat4; /** * Calculates the determinant of a mat4 @@ -1659,7 +2258,7 @@ declare namespace mat4 { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat4): number; /** * Multiplies two mat4's @@ -1669,7 +2268,7 @@ declare namespace mat4 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat4, a: mat4, b: mat4): mat4; /** * Multiplies two mat4's @@ -1679,7 +2278,7 @@ declare namespace mat4 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat4, a: mat4, b: mat4): mat4; /** * Translate a mat4 by the given vector @@ -1689,7 +2288,7 @@ declare namespace mat4 { * @param v vector to translate by * @returns out */ - export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static translate(out: mat4, a: mat4, v: vec3 | number[]): mat4; /** * Scales the mat4 by the dimensions in the given vec3 @@ -1699,7 +2298,7 @@ declare namespace mat4 { * @param v the vec3 to scale the matrix by * @returns out **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static scale(out: mat4, a: mat4, v: vec3 | number[]): mat4; /** * Rotates a mat4 by the given angle @@ -1710,7 +2309,7 @@ declare namespace mat4 { * @param axis the axis to rotate around * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number, axis: GLM.IArray): GLM.IArray; + public static rotate(out: mat4, a: mat4, rad: number, axis: vec3 | number[]): mat4; /** * Rotates a matrix by the given angle around the X axis @@ -1720,7 +2319,7 @@ declare namespace mat4 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateX(out: mat4, a: mat4, rad: number): mat4; /** * Rotates a matrix by the given angle around the Y axis @@ -1730,7 +2329,7 @@ declare namespace mat4 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateY(out: mat4, a: mat4, rad: number): mat4; /** * Rotates a matrix by the given angle around the Z axis @@ -1740,78 +2339,87 @@ declare namespace mat4 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateZ(out: mat4, a: mat4, rad: number): mat4; /** - * Generates a frustum matrix with the given bounds + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): * - * @param out mat4 frustum matrix will be written into - * @param left Left bound of the frustum - * @param right Right bound of the frustum - * @param bottom Bottom bound of the frustum - * @param top Top bound of the frustum - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out + * mat4.identity(dest); + * mat4.translate(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Translation vector + * @returns {mat4} out */ - export function frustum(out: GLM.IArray, left: number, right: number, - bottom: number, top: number, near: number, far: number): GLM.IArray; + public static fromTranslation(out: mat4, v: vec3 | number[]): mat4 /** - * Generates a perspective projection matrix with the given bounds + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): * - * @param out mat4 frustum matrix will be written into - * @param fovy Vertical field of view in radians - * @param aspect Aspect ratio. typically viewport width/height - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out + * mat4.identity(dest); + * mat4.scale(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Scaling vector + * @returns {mat4} out */ - export function perspective(out: GLM.IArray, fovy: number, aspect: number, - near: number, far: number): GLM.IArray; + public static fromScaling(out: mat4, v: vec3 | number[]): mat4 /** - * Generates a orthogonal projection matrix with the given bounds + * Creates a matrix from a given angle around a given axis + * This is equivalent to (but much faster than): * - * @param out mat4 frustum matrix will be written into - * @param left Left bound of the frustum - * @param right Right bound of the frustum - * @param bottom Bottom bound of the frustum - * @param top Top bound of the frustum - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out + * mat4.identity(dest); + * mat4.rotate(dest, dest, rad, axis); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @param {vec3} axis the axis to rotate around + * @returns {mat4} out */ - export function ortho(out: GLM.IArray, left: number, right: number, - bottom: number, top: number, near: number, far: number): GLM.IArray; + public static fromRotation(out: mat4, rad: number, axis: vec3 | number[]): mat4 /** - * Generates a look-at matrix with the given eye position, focal point, and up axis + * Creates a matrix from the given angle around the X axis + * This is equivalent to (but much faster than): * - * @param out mat4 frustum matrix will be written into - * @param eye Position of the viewer - * @param center Point the viewer is looking at - * @param up vec3 pointing up - * @returns out + * mat4.identity(dest); + * mat4.rotateX(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out */ - export function lookAt(out: GLM.IArray, eye: GLM.IArray, - center: GLM.IArray, up: GLM.IArray): GLM.IArray; + public static fromXRotation(out: mat4, rad: number): mat4 /** - * Returns a string representation of a mat4 + * Creates a matrix from the given angle around the Y axis + * This is equivalent to (but much faster than): * - * @param mat matrix to represent as a string - * @returns string representation of the matrix + * mat4.identity(dest); + * mat4.rotateY(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out */ - export function str(mat: GLM.IArray): string; + public static fromYRotation(out: mat4, rad: number): mat4 + /** - * Returns Frobenius norm of a mat4 + * Creates a matrix from the given angle around the Z axis + * This is equivalent to (but much faster than): * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm + * mat4.identity(dest); + * mat4.rotateZ(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out */ - export function frob(a: GLM.IArray): number; + public static fromZRotation(out: mat4, rad: number): mat4 /** * Creates a matrix from a quaternion rotation and vector translation @@ -1828,47 +2436,247 @@ declare namespace mat4 { * @param v Translation vector * @returns out */ - export function fromRotationTranslation(out: GLM.IArray, q: GLM.IArray, v: GLM.IArray): GLM.IArray; - - /** - * Creates a matrix from a quaternion rotation, vector translation and vector scale. - * - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * mat4.scale(dest, scale) - * - * @param out mat4 receiving operation result - * @param q Rotation quaternion - * @param v Translation vector - * @param s Scale vector - * @returns out - */ - export function fromRotationTranslationScale(out: GLM.IArray, q: GLM.IArray, v: GLM.IArray, s: GLM.IArray): GLM.IArray + public static fromRotationTranslation(out: mat4, q: quat, v: vec3 | number[]): mat4; /** - * Creates a matrix from a quaternion + * Returns the translation vector component of a transformation + * matrix. If a matrix is built with fromRotationTranslation, + * the returned vector will be the same as the translation vector + * originally supplied. + * @param {vec3} out Vector to receive translation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + public static getTranslation(out: vec3, mat: mat4): vec3; + + /** + * Returns a quaternion representing the rotational component + * of a transformation matrix. If a matrix is built with + * fromRotationTranslation, the returned quaternion will be the + * same as the quaternion originally supplied. + * @param {quat} out Quaternion to receive the rotation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {quat} out + */ + public static getRotation(out: quat, mat: mat4): quat; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) * * @param out mat4 receiving operation result * @param q Rotation quaternion + * @param v Translation vector + * @param s Scaling vector * @returns out */ - export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; + public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[]): mat4; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * mat4.translate(dest, origin); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * mat4.translate(dest, negativeOrigin); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Rotation quaternion + * @param {vec3} v Translation vector + * @param {vec3} s Scaling vector + * @param {vec3} o The origin vector around which to scale and rotate + * @returns {mat4} out + */ + public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[], o: vec3 | number[]): mat4 + + /** + * Calculates a 4x4 matrix from the given quaternion + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Quaternion to create matrix from + * + * @returns {mat4} out + */ + public static fromQuat(out: mat4, q: quat): mat4 + + /** + * Generates a frustum matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static frustum(out: mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): mat4; + + /** + * Generates a perspective projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param fovy Vertical field of view in radians + * @param aspect Aspect ratio. typically viewport width/height + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static perspective(out: mat4, fovy: number, aspect: number, + near: number, far: number): mat4; + + /** + * Generates a perspective projection matrix with the given field of view. + * This is primarily useful for generating projection matrices to be used + * with the still experimental WebVR API. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + public static perspectiveFromFieldOfView(out: mat4, + fov:{upDegrees: number, downDegrees: number, leftDegrees: number, rightDegrees: number}, + near: number, far: number): mat4 + + /** + * Generates a orthogonal projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static ortho(out: mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): mat4; + + /** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param out mat4 frustum matrix will be written into + * @param eye Position of the viewer + * @param center Point the viewer is looking at + * @param up vec3 pointing up + * @returns out + */ + public static lookAt(out: mat4, eye: vec3 | number[], center: vec3 | number[], up: vec3 | number[]): mat4; + + /** + * Returns a string representation of a mat4 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(mat: mat4): string; + + /** + * Returns Frobenius norm of a mat4 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat4): number; + + /** + * Adds two mat4's + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static add(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static subtract(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static sub(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat4} out + */ + public static multiplyScalar(out: mat4, a: mat4, b: number): mat4 + + /** + * Adds two mat4's after multiplying each element of the second operand by a scalar value. + * + * @param {mat4} out the receiving vector + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat4} out + */ + public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale: number): mat4 + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat4, b: mat4): boolean + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat4, b: mat4): boolean + } // quat -declare namespace quat { +export class quat extends Float32Array { + private typeQuat: number; /** * Creates a new identity quat * * @returns a new quaternion */ - export function create(): GLM.IArray; + public static create(): quat; /** * Creates a new quat initialized with values from an existing quaternion @@ -1877,7 +2685,7 @@ declare namespace quat { * @returns a new quaternion * @function */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: quat): quat; /** * Creates a new quat initialized with the given values @@ -1889,7 +2697,7 @@ declare namespace quat { * @returns a new quaternion * @function */ - export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + public static fromValues(x: number, y: number, z: number, w: number): quat; /** * Copy the values from one quat to another @@ -1899,7 +2707,7 @@ declare namespace quat { * @returns out * @function */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: quat, a: quat): quat; /** * Set the components of a quat to the given values @@ -1912,7 +2720,7 @@ declare namespace quat { * @returns out * @function */ - export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + public static set(out: quat, x: number, y: number, z: number, w: number): quat; /** * Set a quat to the identity quaternion @@ -1920,7 +2728,34 @@ declare namespace quat { * @param out the receiving quaternion * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + public static identity(out: quat): quat; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param {quat} out the receiving quaternion. + * @param {vec3} a the initial vector + * @param {vec3} b the destination vector + * @returns {quat} out + */ + public static rotationTo (out: quat, a: vec3 | number[], b: vec3 | number[]): quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} view the vector representing the viewing direction + * @param {vec3} right the vector representing the local "right" direction + * @param {vec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + public static setAxes (out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat + + /** * Sets a quat from the given angle and rotation axis, @@ -1931,7 +2766,22 @@ declare namespace quat { * @param rad the angle in radians * @returns out **/ - export function setAxisAngle(out: GLM.IArray, axis: GLM.IArray, rad: number): GLM.IArray; + public static setAxisAngle(out: quat, axis: vec3 | number[], rad: number): quat; + + /** + * Gets the rotation axis and angle for a given + * quaternion. If a quaternion is created with + * setAxisAngle, this method will return the same + * values as providied in the original parameter list + * OR functionally equivalent values. + * Example: The quaternion formed by axis [0, 0, 1] and + * angle -90 is the same as the quaternion formed by + * [0, 0, 1] and 270. This method favors the latter. + * @param {vec3} out_axis Vector receiving the axis of rotation + * @param {quat} q Quaternion to be decomposed + * @return {number} Angle, in radians, of the rotation + */ + public static getAxisAngle (out_axis: vec3 | number[], q: quat): number /** * Adds two quat's @@ -1942,7 +2792,7 @@ declare namespace quat { * @returns out * @function */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: quat, a: quat, b: quat): quat; /** * Multiplies two quat's @@ -1952,7 +2802,7 @@ declare namespace quat { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: quat, a: quat, b: quat): quat; /** * Multiplies two quat's @@ -1962,7 +2812,7 @@ declare namespace quat { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: quat, a: quat, b: quat): quat; /** * Scales a quat by a scalar number @@ -1973,7 +2823,7 @@ declare namespace quat { * @returns out * @function */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: quat, a: quat, b: number): quat; /** * Calculates the length of a quat @@ -1982,7 +2832,7 @@ declare namespace quat { * @returns length of a * @function */ - export function length(a: GLM.IArray): number; + public static length(a: quat): number; /** * Calculates the length of a quat @@ -1991,7 +2841,7 @@ declare namespace quat { * @returns length of a * @function */ - export function len(a: GLM.IArray): number; + public static len(a: quat): number; /** * Calculates the squared length of a quat @@ -2000,7 +2850,7 @@ declare namespace quat { * @returns squared length of a * @function */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: quat): number; /** * Calculates the squared length of a quat @@ -2009,7 +2859,7 @@ declare namespace quat { * @returns squared length of a * @function */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: quat): number; /** * Normalize a quat @@ -2019,7 +2869,7 @@ declare namespace quat { * @returns out * @function */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: quat, a: quat): quat; /** * Calculates the dot product of two quat's @@ -2029,7 +2879,7 @@ declare namespace quat { * @returns dot product of a and b * @function */ - export function dot(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: quat, b: quat): number; /** * Performs a linear interpolation between two quat's @@ -2041,7 +2891,7 @@ declare namespace quat { * @returns out * @function */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: quat, a: quat, b: quat, t: number): quat; /** * Performs a spherical linear interpolation between two quat @@ -2052,7 +2902,20 @@ declare namespace quat { * @param t interpolation amount between the two inputs * @returns out */ - export function slerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static slerp(out: quat, a: quat, b: quat, t: number): quat; + + /** + * Performs a spherical linear interpolation with two control points + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {quat} c the third operand + * @param {quat} d the fourth operand + * @param {number} t interpolation amount + * @returns {quat} out + */ + public static sqlerp(out: quat, a: quat, b: quat, c: quat, d: quat, t: number): quat; /** * Calculates the inverse of a quat @@ -2061,7 +2924,7 @@ declare namespace quat { * @param a quat to calculate inverse of * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: quat, a: quat): quat; /** * Calculates the conjugate of a quat @@ -2071,15 +2934,15 @@ declare namespace quat { * @param a quat to calculate conjugate of * @returns out */ - export function conjugate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static conjugate(out: quat, a: quat): quat; /** - * Returns a string representation of a quatenion + * Returns a string representation of a quaternion * - * @param vec vector to represent as a string - * @returns string representation of the vector + * @param a quat to represent as a string + * @returns string representation of the quat */ - export function str(a: GLM.IArray): string; + public static str(a: quat): string; /** * Rotates a quaternion by the given angle about the X axis @@ -2089,7 +2952,7 @@ declare namespace quat { * @param rad angle (in radians) to rotate * @returns out */ - export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateX(out: quat, a: quat, rad: number): quat; /** * Rotates a quaternion by the given angle about the Y axis @@ -2099,7 +2962,7 @@ declare namespace quat { * @param rad angle (in radians) to rotate * @returns out */ - export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateY(out: quat, a: quat, rad: number): quat; /** * Rotates a quaternion by the given angle about the Z axis @@ -2109,7 +2972,7 @@ declare namespace quat { * @param rad angle (in radians) to rotate * @returns out */ - export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateZ(out: quat, a: quat, rad: number): quat; /** * Creates a quaternion from the given 3x3 rotation matrix. @@ -2122,20 +2985,20 @@ declare namespace quat { * @returns out * @function */ - export function fromMat3(out: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static fromMat3(out: quat, m: mat3): quat; /** * Sets the specified quaternion with values corresponding to the given * axes. Each axis is a vec3 and is expected to be unit length and * perpendicular to all other specified axes. * + * @param out the receiving quat * @param view the vector representing the viewing direction * @param right the vector representing the local "right" direction * @param up the vector representing the local "up" direction * @returns out */ - export function setAxes(out: GLM.IArray, view: GLM.IArray, right: GLM.IArray, - up: GLM.IArray): GLM.IArray; + public static setAxes(out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat; /** * Sets a quaternion to represent the shortest rotation from one @@ -2148,7 +3011,7 @@ declare namespace quat { * @param b the destination vector * @returns out */ - export function rotationTo(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static rotationTo(out: quat, a: vec3 | number[], b: vec3 | number[]): quat; /** * Calculates the W component of a quat from the X, Y, and Z components. @@ -2159,5 +3022,23 @@ declare namespace quat { * @param a quat to calculate W component of * @returns out */ - export function calculateW(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static calculateW(out: quat, a: quat): quat; + + /** + * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + public static exactEquals (a: quat, b: quat): boolean; + + /** + * Returns whether or not the quaternions have approximately the same elements in the same position. + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + public static equals (a: quat, b: quat): boolean; } From bf341749b4ebbd7242e452ef720ba2580316cf6c Mon Sep 17 00:00:00 2001 From: Erwin Poeze Date: Tue, 16 Aug 2016 08:38:54 +0200 Subject: [PATCH 037/844] ramda typings --- ramda/ramda-tests.ts | 1952 ++++++++++++++++++++++++++++++++++++++++++ ramda/ramda.d.ts | 1807 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 3759 insertions(+) create mode 100644 ramda/ramda-tests.ts create mode 100644 ramda/ramda.d.ts diff --git a/ramda/ramda-tests.ts b/ramda/ramda-tests.ts new file mode 100644 index 0000000000..15ec5eb274 --- /dev/null +++ b/ramda/ramda-tests.ts @@ -0,0 +1,1952 @@ +import * as R from './ramda'; + +var double = function(x: number): number { + return x + x +}; + +var shout = function(x: number): string { + return x >= 10 + ? 'big' + : 'small' +}; + +class F { + x = 'X'; + y = 'Y'; +} +class F2 { + a = 100; + y = 1; + x(){}; + z() {}; +} + +(() => { + var x: boolean; + x = R.isArrayLike('a'); + x = R.isArrayLike([1,2,3]); + x = R.isArrayLike([]); +}); + +(() => { + R.propIs(Number, 'x', {x: 1, y: 2}); //=> true + R.propIs(Number, 'x')({x: 1, y: 2}); //=> true + R.propIs(Number)('x', {x: 1, y: 2}); //=> true + R.propIs(Number)('x')({x: 1, y: 2}); //=> true + R.propIs(Number, 'x', {x: 'foo'}); //=> false + R.propIs(Number, 'x', {}); //=> false +}); + +(() => { + R.type({}); //=> "Object" + R.type(1); //=> "Number" + R.type(false); //=> "Boolean" + R.type('s'); //=> "String" + R.type(null); //=> "Null" + R.type([]); //=> "Array" + R.type(/[A-z]/); //=> "RegExp" +}); + +() => { + var takesNoArg = function() { return true; }; + var takesOneArg = function(a: number) { return [a]; }; + var takesTwoArgs = function(a: number, b: number) { return [a, b]; }; + var takesThreeArgs = function(a: number, b: number, c: number) { return [a, b, c]; }; + + var addFourNumbers = function(a: number, b: number, c: number, d: number): number { + return a + b + c + d; + }; + + var x1: Function = R.curry(addFourNumbers) + // because of the current way of currying, the following call results in a type error + // var x2: Function = R.curry(addFourNumbers)(1,2,4) + var x3: Function = R.curry(addFourNumbers)(1)(2) + var x4: Function = R.curry(addFourNumbers)(1)(2)(3) + var y1: number = R.curry(addFourNumbers)(1)(2)(3)(4) + var y2: number = R.curry(addFourNumbers)(1,2)(3,4) + var y3: number = R.curry(addFourNumbers)(1,2,3)(4) + + R.nAry(0, takesNoArg); + R.nAry(0, takesOneArg); + R.nAry(1, takesTwoArgs); + R.nAry(1, takesThreeArgs); + + var u1: {(a: any): any} = R.unary(takesOneArg); + var u2: {(a: any): any} = R.unary(takesTwoArgs); + var u3: {(a: any): any} = R.unary(takesThreeArgs); + + R.binary(takesTwoArgs); + R.binary(takesThreeArgs); + + var addTwoNumbers = function(a:number, b:number) { return a + b; } + var addTwoNumbersCurried = R.curry(addTwoNumbers); + + var inc = addTwoNumbersCurried(1); + var z1:number = inc(2); + var z2:number = addTwoNumbersCurried(2,3); +} + +() => { + const addFour = (a:number) => (b:number) => (c:number) => (d:number) => a + b + c + d; + const uncurriedAddFour = R.uncurryN(4, addFour); + const res: number = uncurriedAddFour(1, 2, 3, 4); //=> 10 +} + +() => { + // coerceArray :: (a|[a]) -> [a] + const coerceArray = R.unless(R.isArrayLike, R.of); + const a: number[] = coerceArray([1, 2, 3]); //=> [1, 2, 3] + const b: number[] = coerceArray(1); //=> [1] +} + +(() => { + R.nthArg(1)('a', 'b', 'c'); //=> 'b' + R.nthArg(-1)('a', 'b', 'c'); //=> 'c' +}); + +() => { + const fn: (...args: string[])=>string = R.unapply(JSON.stringify); + const res: string = R.unapply(JSON.stringify)(1, 2, 3); //=> '[1,2,3]' +} + +() => { + const a: number = R.until(R.flip(R.gt)(100), R.multiply(2))(1) // => 128 +} + +() => { + const truncate = R.when( + R.propSatisfies(R.flip(R.gt)(10), 'length'), + R.pipe(R.take(10), R.append('…'), R.join('')) + ); + const a: string = truncate('12345'); //=> '12345' + const b: string = truncate('0123456789ABC'); //=> '0123456789…' +} + +/* compose */ +() => { + var double = function(x: number): number { + return x + x + } + var limit10 = function(x: number): boolean { + return x >= 10 + } + var func: (x: number) => boolean = R.compose(limit10, double) + var res: boolean = R.compose(limit10, double)(10) + + const f0 = (s: string) => +s; // string -> number + const f1 = (n: number) => n === 1; // number -> boolean + const f2 = R.compose(f1, f0); // string -> boolean + + // akward example that bounces types between number and string + const g0 = (list: number[]) => R.map(R.inc, list); + const g1 = R.dropWhile(R.gt(10)); + const g2 = R.map((i: number) => i > 5 ? 'bigger' : 'smaller'); + const g3 = R.all((i: string) => i === 'smaller'); + const g = R.compose(g3, g2, g1, g0); + const g_res: boolean = g([1, 2, 10, 13]); +} + +/* pipe */ +() => { + var func: (x: number) => string = R.pipe(double, double, shout) + var res: string = R.pipe(double, double, shout)(10); + + const capitalize = (str: string) => R.pipe( + R.split(''), + R.adjust(R.toUpper, 0), + R.join('') + )(str); + + var f = R.pipe(Math.pow, R.negate, R.inc); + var fr: number = f(3, 4); // -(3^4) + 1 +} + +() => { + R.invoker('charAt', String.prototype); + R.invoker('charAt', String.prototype, 1); +} + +(() => { + const range = R.juxt([Math.min, Math.max]); + range(3, 4, 9, -3); //=> [-3, 9] + + const chopped = R.juxt([R.head, R.last]); + chopped('longstring'); // => ["l", "g"] +}); + +var square = function(x: number) { return x * x; }; +var add = function(a: number, b: number) { return a + b; }; +// Adds any number of arguments together +var addAll = function() { + return 0; +}; + +// Basic example +R.useWith(addAll, [ double, square ]); + +(() => { + var printXPlusFive = function(x: number) { console.log(x + 5); }; + R.forEach(printXPlusFive, [1, 2, 3]); + R.clone([{},{},{}]) + R.clone([1,2,3]); +})(); + +// (() => { +// var printXPlusFive = function(x, i) { console.log(i + 5); }; +// R.forEach.idx(printXPlusFive, [{name: 1}, {name: 2}, {name: 3}]); +// })(); + +var i = function(x: number) {return x;}; +R.times(i, 5); + +(() => { + var triple = function(x: number): number { return x * 3; }; + var square = function(x: number): number { return x * x; }; + var squareThenDoubleThenTriple = R.pipe(square, double, triple); + squareThenDoubleThenTriple(5); //=> 150 + + +})(); + +(() => { + var multiply = function(a: number, b: number) { return a * b; }; + var double = R.partial(multiply, 2); + double(2); //=> 4 + + var greet = function(salutation: string, title: string, firstName: string, lastName: string) { + return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; + }; + var sayHello = R.partial(greet, 'Hello'); + var sayHelloToMs = R.partial(sayHello, 'Ms.'); + sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!' + + var greetMsJaneJones = R.partialRight(greet, 'Ms.', 'Jane', 'Jones'); + greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!' +})(); + +(() => { + var numberOfCalls = 0; + var trackedAdd = function(a: number, b: number) { + numberOfCalls += 1; + return a + b; + }; + var memoTrackedAdd = R.memoize(trackedAdd); + + memoTrackedAdd(1, 2); //=> 3 + numberOfCalls; //=> 1 + memoTrackedAdd(1, 2); //=> 3 + numberOfCalls; //=> 1 + memoTrackedAdd(2, 3); //=> 5 + numberOfCalls; //=> 2 + + // Note that argument order matters + memoTrackedAdd(2, 1); //=> 3 + numberOfCalls; //=> 3 +})(); + +(() => { + var addOneOnce = R.once(function(x: number){ return x + 1; }); + addOneOnce(10); //=> 11 + addOneOnce(addOneOnce(50)); //=> 11 +})(); + +(() => { + var slashify = R.wrap(R.flip(R.add)('/'), function(f: Function, x: string) { + return R.match(/\/$/, x) ? x : f(x); + }); + + slashify('a'); //=> 'a/' + slashify('a/'); //=> 'a/' +})(); + + + +(() => { + var numbers = [1, 2, 3]; + var add = function(a: number, b: number) { + return a + b + }; + R.reduce(add, 10, numbers); //=> 16; +})(); + +(() => { + var plus3 = R.add(3); +})(); + +(() => { + var pairs = [ ['a', 1], ['b', 2], ['c', 3] ]; + var flattenPairs = function(acc: [string, number], pair: [string, number]) { + return acc.concat(pair); + }; + R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] +})(); + +(() => { + var values = { x: 1, y: 2, z: 3 }; + var prependKeyAndDouble = function(num: number, key: string, obj: any) { + return key + (num * 2); + }; + R.mapObjIndexed(prependKeyAndDouble, values); //=> { x: 'x2', y: 'y4', z: 'z6' } +}); + +(() => { + const a: number[] = R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6] + const b: number[][] = R.of([1]); //=> [[1]] + const c: number[] = R.of(1); + +}); + +() => { + const a1 = R.empty([1,2,3,4,5]); //=> [] + const a2 = R.empty([1, 2, 3]); //=> [] + const a3 = R.empty('unicorns'); //=> '' + const a4 = R.empty({x: 1, y: 2}); //=> {} +} + +(() => { + R.length([1, 2, 3]); //=> 3 +}); + +(() => { + const isEven = function(n: number) { + return n % 2 === 0; + }; + const filterIndexed = R.addIndex(R.filter); + + R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4] + + var lastTwo = function(val: number, idx: number, list: number[]) { + return list.length - idx <= 2; + }; + filterIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [0, 9] + + var isOdd = function(n: number) { + return n % 2 === 1; + }; + R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] +}); +(() => { + var isNotFour = function(x: number) { + return !(x === 4); + }; + R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3] + R.take(2, [1, 2, 3, 4]); //=> [1, 2] +}); +(() => { + var f = function(n: number) { return n > 50 ? false : [-n, n + 10] }; + let a = R.unfold(f, 10); //=> [-10, -20, -30, -40, -50] + let b = R.unfold(f); //=> [-10, -20, -30, -40, -50] + let c = b(10); +}); +/***************************************************************** + * Function category + */ + + + () => { + var mergeThree = function(a: number, b: number, c: number): number[] { + return ([]).concat(a, b, c); + }; + mergeThree(1, 2, 3); //=> [1, 2, 3] + var flipped = R.flip(mergeThree); + flipped(1, 2, 3); //=> [2, 1, 3] + } + +/********************* + * List category + ********************/ +() => { + var lessThan2 = R.flip(R.lt)(2); + var lessThan3 = R.flip(R.lt)(3); + R.all(lessThan2)([1, 2]); //=> false + R.all(lessThan3)([1, 2]); //=> true +} + +() => { + var lessThan0 = R.flip(R.lt)(0); + var lessThan2 = R.flip(R.lt)(2); + R.any(lessThan0)([1, 2]); //=> false + R.any(lessThan2)([1, 2]); //=> true +} + +() => { + R.aperture(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [2, 3], [3, 4], [4, 5]] + R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]] + R.aperture(7, [1, 2, 3, 4, 5]); //=> [] + R.aperture(7)([1, 2, 3, 4, 5]); //=> [] +} + +() => { + R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests'] + R.append('tests')(['write', 'more']); //=> ['write', 'more', 'tests'] + R.append('tests', []); //=> ['tests'] + R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']] + R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']] + R.append(['tests'])(['write', 'more']); //=> ['write', 'more', ['tests']] + R.append(['tests'])(['write', 'more']); //=> ['write', 'more', ['tests']] +} + +() => { + var duplicate = function(n: number) { + return [n, n]; + }; + R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3] + R.chain(duplicate)([1, 2, 3]); //=> [1, 1, 2, 2, 3, 3] +} + +() => { + R.clamp(1, 10, -1) // => 1 + R.clamp(1, 10)(11) // => 10 + R.clamp(1)(10, 4) // => 4 + R.clamp('a', 'd', 'e') // => 'd' +} + +() => { + R.concat([], []); //=> [] + R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] + R.concat([4, 5, 6])([1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] + R.concat('ABC')('DEF'); // 'ABCDEF' +} + +() => { + R.contains(3)([1, 2, 3]); //=> true + R.contains(3, [1, 2, 3]); //=> true + R.contains(4)([1, 2, 3]); //=> false + R.contains({})([{}, {}]); //=> false + var obj = {}; + R.contains(obj)([{}, obj, {}]); //=> true +} + +() => { + R.drop(3, [1,2,3,4,5,6,7]); //=> [4,5,6,7] + R.drop(3)([1,2,3,4,5,6,7]); //=> [4,5,6,7] + R.drop(3, 'ramda'); //=> 'ram' + R.drop(3)('ramda'); //=> 'ram' +} + +(() => { + R.dropLast(1, ['foo', 'bar', 'baz']); //=> ['foo', 'bar'] + R.dropLast(2)(['foo', 'bar', 'baz']); //=> ['foo'] + R.dropLast(3, 'ramda'); //=> 'ra' + R.dropLast(3)('ramda'); //=> 'ra' +}); + +(() => { + var lteThree = (x: number) => x <= 3; + R.dropLastWhile(lteThree, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3, 4] +}); + +() => { + var lteTwo = function(x: number) { + return x <= 2; + }; + R.dropWhile(lteTwo, [1, 2, 3, 4]); //=> [3, 4] + R.dropWhile(lteTwo)([1, 2, 3, 4]); //=> [3, 4] +} + +() => { + var isEven = function(n: number) { + return n % 2 === 0; + }; + R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4] + var isEvenFn = R.filter(isEven); + isEvenFn([1, 2, 3, 4]); +} + +() => { + var lastTwo = function(val: number, idx: number, list: number[]) { + return list.length - idx <= 2; + }; + var filterIndexed = R.addIndex(R.filter); + + filterIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [0, 9] + var lastTwoFn = filterIndexed(lastTwo); + lastTwoFn([8, 6, 7, 5, 3, 0, 9]); +} + +() => { + var xs = [{a: 1}, {a: 2}, {a: 3}]; + R.find(R.propEq('a', 2))(xs); //=> {a: 2} + R.find(R.propEq('a', 4))(xs); //=> undefined +} + +() => { + var xs = [{a: 1}, {a: 2}, {a: 3}]; + R.findIndex(R.propEq('a', 2))(xs); //=> 1 + R.findIndex(R.propEq('a', 4))(xs); //=> -1 + + R.findIndex((x: number) => x === 1, [1, 2, 3]); +} + +() => { + var xs = [{a: 1, b: 0}, {a:1, b: 1}]; + R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1} + R.findLast(R.propEq('a', 4))(xs); //=> undefined +} + +() => { + var xs = [{a: 1, b: 0}, {a:1, b: 1}]; + R.findLastIndex(R.propEq('a', 1))(xs); //=> 1 + R.findLastIndex(R.propEq('a', 4))(xs); //=> -1 + R.findLastIndex((x: number) => x === 1, [1, 2, 3]); +} +() => { + var user1 = { address: { zipCode: 90210 } }; + var user2 = { address: { zipCode: 55555 } }; + var user3 = { name: 'Bob' }; + var users = [ user1, user2, user3 ]; + var isFamous = R.pathEq(['address', 'zipCode'], 90210); + R.filter(isFamous, users); //=> [ user1 ] +} +() => { + var xs: {[key:string]: string} = {a: '1', b: '0'}; + R.propEq('a', '1', xs);//=> true + R.propEq('a', '4', xs); //=> false +} +() => { + var xs: {[key:string]: number} = {a: 1, b: 0}; + R.propEq('a', 1, xs);//=> true + R.propEq('a', 4, xs); //=> false +} +() => { + var xs = {a: '1', b: '0'}; + R.propEq('a', '1', xs);//=> true + R.propEq('a', '4', xs); //=> false +} +() => { + var xs = {a: 1, b: 0}; + R.propEq('a', 1, xs);//=> true + R.propEq('a', 4, xs); //=> false +} + +interface Obj { a: number; b: number }; +() => { + var xs: Obj = {a: 1, b: 0}; + R.propEq('a', 1, xs);//=> true + R.propEq('a', 4, xs); //=> false +} + +() => { + R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]); + //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] +} + +() => { + var printXPlusFive = function(x: number) { console.log(x + 5); }; + R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3] + R.forEach(printXPlusFive)([1, 2, 3]); //=> [1, 2, 3] + //-> 6 + //-> 7 + //-> 8 +} + +() => { + var plusFive = function(num: number, idx: number, list: number[]) { list[idx] = num + 5 }; + R.addIndex(R.forEach)(plusFive)([1, 2, 3]); //=> [6, 7, 8] +} + +() => { + var byGrade = R.groupBy(function(student: {score: number; name: string}) { + var score = student.score; + return score < 65 ? 'F' : + score < 70 ? 'D' : + score < 80 ? 'C' : + score < 90 ? 'B' : 'A'; + }); + var students = [{name: 'Abby', score: 84}, + {name: 'Eddy', score: 58}, + {name: 'Jack', score: 69}]; + byGrade(students); +} + +() => { + R.groupWith(R.equals, [0, 1, 1, 2, 3, 5, 8, 13, 21]) + // [[0], [1, 1], [2, 3, 5, 8, 13, 21]] + + R.groupWith((a: number, b: number) => a % 2 === b % 2, [0, 1, 1, 2, 3, 5, 8, 13, 21]) + // [[0], [1, 1], [2], [3, 5], [8], [13, 21]] + + const isVowel = (a: string) => R.contains(a, 'aeiou') ? a : ''; + R.groupWith(R.eqBy(isVowel), 'aestiou') + // ['ae', 'st', 'iou'] +} + +() => { + R.head(['fi', 'fo', 'fum']); //=> 'fi' + R.head([10, 'ten']); // => 10 + R.head(['10', 10]); // => '10' +} + +(() => { + let list = [{id: 'xyz', title: 'A'}, {id: 'abc', title: 'B'}]; + const a1 = R.indexBy(R.prop('id'), list); + const a2 = R.indexBy(R.prop('id'))(list); + const a3 = R.indexBy<{id:string}>(R.prop('id'))(list); +}); + +() => { + R.indexOf(3, [1,2,3,4]); //=> 2 + R.indexOf(10)([1,2,3,4]); //=> -1 +} + +() => { + R.init(['fi', 'fo', 'fum']); //=> ['fi', 'fo'] +} + +() => { + R.insert(2, 5, [1,2,3,4]); //=> [1,2,5,3,4] + R.insert(2)(5, [1,2,3,4]); //=> [1,2,5,3,4] + R.insert(2, 5)([1,2,3,4]); //=> [1,2,5,3,4] +} + +() => { + R.insertAll(2, [10,11,12], [1,2,3,4]); + R.insertAll(2)([10,11,12], [1,2,3,4]); + R.insertAll(2, [10,11,12])([1,2,3,4]); +} + +() => { + var numbers = [1, 2, 3, 4]; + var transducer = R.compose(R.map(R.add(1)), R.take(2)); + + R.into([], transducer, numbers); //=> [2, 3] + + var intoArray = R.into([]); + intoArray(transducer, numbers); //=> [2, 3] +} + +() => { + var spacer = R.join(' '); + spacer(['a', 2, 3.4]); //=> 'a 2 3.4' + R.join('|', [1, 2, 3]); //=> '1|2|3' +} + +() => { + R.last(['fi', 'fo', 'fum']); //=> 'fum' +} + +() => { + R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6 + R.lastIndexOf(10, [1,2,3,4]); //=> -1 +} + +() => { + R.length([]); //=> 0 + R.length([1, 2, 3]); //=> 3 +} + +() => { + var headLens = R.lensIndex(0); + headLens([10, 20, 30, 40]); //=> 10 + headLens.set('mu', [10, 20, 30, 40]); //=> ['mu', 20, 30, 40] + R.view(headLens, ['a', 'b', 'c']); //=> 'a' + R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c'] + R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c'] +} + +() => { + var double = function(x: number) { + return x * 2; + }; + R.map(double, [1, 2, 3]); //=> [2, 4, 6] + + // functor + const stringFunctor = { + map: (fn: (c: number) => number) => { + var chars = "Ifmmp!Xpsme".split(""); + return chars.map((char) => String.fromCharCode(fn(char.charCodeAt(0)))).join(""); + } + }; + R.map((x: number) => x-1, stringFunctor); // => "Hello World" +} + +() => { + var digits = ['1', '2', '3', '4']; + var append = function(a: string, b: string): [string, string]{ + return [a + b, a + b]; + } + R.mapAccum(append, '0', digits); //=> ['01234', ['01', '012', '0123', '01234']] + R.mapAccum(append)('0', digits); //=> ['01234', ['01', '012', '0123', '01234']] + R.mapAccum(append, '0')(digits); //=> ['01234', ['01', '012', '0123', '01234']] +} + +() => { + var digits = ['1', '2', '3', '4']; + var append = function(a: string, b: string): [string, string] { + return [a + b, a + b]; + } + + R.mapAccumRight(append, '0', digits); //=> ['04321', ['04321', '0432', '043', '04']] + R.mapAccumRight(append)('0', digits); //=> ['04321', ['04321', '0432', '043', '04']] + R.mapAccumRight(append, '0')(digits); //=> ['04321', ['04321', '0432', '043', '04']] +} + +() => { + var squareEnds = function(elt: number, idx: number, list: number[]) { + if (idx === 0 || idx === list.length - 1) { + return elt * elt; + } + return elt; + }; + R.addIndex(R.map)(squareEnds, [8, 5, 3, 0, 9]); //=> [64, 5, 3, 0, 81] + R.addIndex(R.map)(squareEnds)([8, 5, 3, 0, 9]); //=> [64, 5, 3, 0, 81] +} + +() => { + R.none(R.isNaN, [1, 2, 3]); //=> true + R.none(R.isNaN, [1, 2, 3, NaN]); //=> false + R.none(R.isNaN)([1, 2, 3, NaN]); //=> false +} + +() => { + var list = ['foo', 'bar', 'baz', 'quux']; + R.nth(1, list); //=> 'bar' + R.nth(-1, list); //=> 'quux' + R.nth(-99, list); //=> undefined + R.nth(-99)(list); //=> undefined +} + +() => { + R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']); + R.partition(R.contains('s'))(['sss', 'ttt', 'foo', 'bars']); + R.partition((x: number) => x > 2, [1, 2, 3, 4]); + R.partition((x: number) => x > 2)([1, 2, 3, 4]); +} + +() => { + const a = R.pluck('a')([{a: 1}, {a: 2}]); //=> [1, 2] + const b = R.pluck(0)([[1, 2], [3, 4]]); //=> [1, 3] +} + +() => { + R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum'] + R.prepend('fee')(['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum'] +} + +() => { + R.range(1, 5); //=> [1, 2, 3, 4] + R.range(50)(53); //=> [50, 51, 52] +} + +() => { + var numbers = [1, 2, 3]; + var add = function(a: number, b: number) { + return a + b; + }; + R.reduce(add, 10, numbers); //=> 16 + R.reduce(add)(10, numbers); //=> 16 + R.reduce(add, 10)(numbers); //=> 16 +} + +interface Student { + name: string; + score: number; +} +() => { + const reduceToNamesBy = R.reduceBy((acc: string[], student: Student) => acc.concat(student.name), []); + const namesByGrade = reduceToNamesBy(function(student) { + let score = student.score; + return score < 65 ? 'F' : + score < 70 ? 'D' : + score < 80 ? 'C' : + score < 90 ? 'B' : 'A'; + }); + let students = [{name: 'Lucy', score: 92}, + {name: 'Drew', score: 85}, + {name: 'Bart', score: 62}]; + const names = namesByGrade(students); + // { + // 'A': ['Lucy'], + // 'B': ['Drew'] + // 'F': ['Bart'] + // } +} + +() => { + var reduceIndexed = R.addIndex(R.reduce); + var letters = ['a', 'b', 'c']; + var objectify = function(accObject: {[elem:string]: number}, elem: string, idx: number, list: string[]) { + accObject[elem] = idx; + return accObject; + }; + reduceIndexed(objectify, {}, letters); //=> { 'a': 0, 'b': 1, 'c': 2 } + reduceIndexed(objectify)({}, letters); //=> { 'a': 0, 'b': 1, 'c': 2 } + reduceIndexed(objectify, {})(letters); //=> { 'a': 0, 'b': 1, 'c': 2 } +} + +interface KeyValuePair extends Array { 0 : K; 1 : V; } +type Pair = KeyValuePair +() => { + var pairs: Pair[] = [ ['a', 1], ['b', 2], ['c', 3] ]; + var flattenPairs = function(acc: Pair[], pair: Pair): Pair[] { + return acc.concat(pair); + }; + R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] + R.reduceRight(flattenPairs, [])(pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] + R.reduceRight(flattenPairs)([], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] +} + +() => { + var isOdd = function(n: number) { + return n % 2 === 1; + }; + R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] + R.reject(isOdd)([1, 2, 3, 4]); //=> [2, 4] +} + +() => { + const lastTwo = function(val: number, idx: number, list: number[]) { + return list.length - idx <= 2; + }; + const rejectIndexed = R.addIndex(R.reject); + rejectIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [8, 6, 7, 5, 3] + rejectIndexed(lastTwo)([8, 6, 7, 5, 3, 0, 9]); //=> [8, 6, 7, 5, 3] +} + +() => { + R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] + R.remove(2, 3)([1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] + R.remove(2)(3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] +} + +() => { + R.repeat('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi'] + var obj = {}; + var repeatedObjs = R.repeat(obj, 5); //=> [{}, {}, {}, {}, {}] + repeatedObjs[0] === repeatedObjs[1]; //=> true +} + +() => { + R.reverse([1, 2, 3]); //=> [3, 2, 1] + R.reverse([1, 2]); //=> [2, 1] + R.reverse([1]); //=> [1] + R.reverse([]); //=> [] +} + +() => { + var numbers = [1, 2, 3, 4]; + R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24] + R.scan(R.multiply, 1)(numbers); //=> [1, 1, 2, 6, 24] + R.scan(R.multiply)(1, numbers); //=> [1, 1, 2, 6, 24] +} + +() => { + var xs = R.range(0, 10); + R.slice(2, 5, xs); //=> [2, 3, 4] + R.slice(2, 5)(xs); //=> [2, 3, 4] + R.slice(2)(5, xs); //=> [2, 3, 4] + + var str = 'Hello World'; + R.slice(2, 5, str); //=> 'llo' + R.slice(2, 5)(str); //=> 'llo' + R.slice(2)(5, str); //=> 'llo' +} + +() => { + var diff = function(a: number, b: number) { return a - b; }; + R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7] + R.sort(diff)([4,2,7,5]); //=> [2, 4, 5, 7] +} + +() => { + const fn = R.cond([ + [R.equals(0), R.always('water freezes at 0°C')], + [R.equals(100), R.always('water boils at 100°C')], + [R.T, (temp: number) => 'nothing special happens at ' + temp + '°C'] + ]); + const a: string = fn(0); //=> 'water freezes at 0°C' + const b: string = fn(50); //=> 'nothing special happens at 50°C' + const c: string = fn(100); //=> 'water boils at 100°C' +} + +() => { + R.tail(['fi', 'fo', 'fum']); //=> ['fo', 'fum'] + R.tail([1, 2, 3]); //=> [2, 3] +} + +() => { + R.take(3,[1,2,3,4,5]); //=> [1,2,3] + + var members= [ "Paul Desmond","Bob Bates","Joe Dodge","Ron Crotty","Lloyd Davis","Joe Morello","Norman Bates", + "Eugene Wright","Gerry Mulligan","Jack Six","Alan Dawson","Darius Brubeck","Chris Brubeck", + "Dan Brubeck","Bobby Militello","Michael Moore","Randy Jones"]; + var takeFive = R.take(5); + takeFive(members); //=> ["Paul Desmond","Bob Bates","Joe Dodge","Ron Crotty","Lloyd Davis"] +} +() => { + R.take(3,"Example"); //=> "Exa" + + var takeThree = R.take(3); + takeThree("Example"); //=> "Exa" +} + + + +() => { + const a: string[] = R.takeLast(1, ['foo', 'bar', 'baz']); //=> ['baz'] + const b: string[] = R.takeLast(2)(['foo', 'bar', 'baz']); //=> ['bar', 'baz'] + const c: string = R.takeLast(3, 'ramda'); //=> 'mda' + const d: string = R.takeLast(3)('ramda'); //=> 'mda' +} + +() => { + const isNotOne = (x: number) => x !== 1; + const a: number[] = R.takeLastWhile(isNotOne, [1, 2, 3, 4]); //=> [2, 3, 4] + const b: number[] = R.takeLastWhile(isNotOne)([1, 2, 3, 4]); //=> [2, 3, 4] +} + +() => { + var isNotFour = function(x: number) { + return !(x === 4); + }; + + R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3] + R.takeWhile(isNotFour)([1, 2, 3, 4]); //=> [1, 2, 3] +} + +() => { + const sayX = (x: number) => console.log('x is ' + x); + const a: number = R.tap(sayX, 100); //=> 100 +} + +() => { + const a: boolean = R.test(/^x/, 'xyz'); //=> true + const b: boolean = R.test(/^y/)('xyz'); //=> false +} + +() => { + const a1 = R.times(R.identity, 5); //=> [0, 1, 2, 3, 4] + const a2 = R.times(R.identity)(5); //=> [0, 1, 2, 3, 4] +} + +() => { + class Point { + constructor(public x: number, public y: number) { + this.x = x; + this.y = y; + } + toStringn() { + return 'new Point(' + this.x + ', ' + this.y + ')'; + } + }; + R.toString(new Point(1, 2)); //=> 'new Point(1, 2)' + + R.toString(42); //=> '42' + R.toString('abc'); //=> '"abc"' + R.toString([1, 2, 3]); //=> '[1, 2, 3]' + R.toString({foo: 1, bar: 2, baz: 3}); //=> '{"bar": 2, "baz": 3, "foo": 1}' + R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date("2001-02-03T04:05:06.000Z")' +} + +() => { + var numbers = [1, 2, 3, 4]; + var transducer = R.compose(R.map(R.add(1)), R.take(2)); + var fn = R.flip(R.append); + R.transduce(transducer, fn, [], numbers); //=> [2, 3] + R.transduce(transducer, fn, [])(numbers); //=> [2, 3] + R.transduce(transducer, fn)([], numbers); //=> [2, 3] + R.transduce(transducer)(fn, [], numbers); //=> [2, 3] +} + +() => { + const a: any[][] = R.transpose([[1, 'a'], [2, 'b'], [3, 'c']]) //=> [[1, 2, 3], ['a', 'b', 'c']] + const b: any[][] = R.transpose([[1, 2, 3], ['a', 'b', 'c']]) //=> [[1, 'a'], [2, 'b'], [3, 'c']] + const c: any[][] = R.transpose([[10, 11], [20], [], [30, 31, 32]]) //=> [[10, 20, 30], [11, 31], [32]] +} + +() => { + const x = R.prop('x'); + const a: boolean = R.tryCatch(R.prop('x'), R.F, {x: true}); //=> true + const b: boolean = R.tryCatch(R.prop('x'), R.F, null); //=> false +} + +() => { + R.uniq([1, 1, 2, 1]); //=> [1, 2] + R.uniq([{}, {}]); //=> [{}, {}] + R.uniq([1, '1']); //=> [1, '1'] +} + +() => { + var strEq = function(a: any, b: any) { return String(a) === String(b); }; + R.uniqWith(strEq, [1, '1', 2, 1]); //=> [1, 2] + R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2] + R.uniqWith(strEq)([{}, {}]); //=> [{}] + R.uniqWith(strEq)([1, '1', 1]); //=> [1] + R.uniqWith(strEq)(['1', 1, 1]); //=> ['1'] +} + +() => { + R.equals(R.unnest([1, [2], [[3]]]), [1,2,[3]]); //=> true + R.equals(R.unnest([[1, 2], [3, 4], [5, 6]]),[1,2,3,4,5,6]); //=> true +} + +() => { + R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] + R.xprod([1, 2])(['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] +} + +() => { + R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']] + R.zip([1, 2, 3])(['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']] +} + +() => { + R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3} + R.zipObj(['a', 'b', 'c'])([1, 2, 3]); //=> {a: 1, b: 2, c: 3} +} + +() => { + var f = function(x:number, y:string) { + // ... + }; + R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']); //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] + R.zipWith(f)([1, 2, 3], ['a', 'b', 'c']); //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] + R.zipWith(f, [1, 2, 3])(['a', 'b', 'c']); //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] +} + +/***************************************************************** + * Object category + */ +() => { + const a = R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} + const b = R.assoc('c')(3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} + const c = R.assoc('c', 3)({a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} +} + +() => { + const a1 = R.dissoc<{a:number, c:number}>('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} + const a2 = R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} + const a4 = R.dissoc('b')<{a:number, c:number}>({a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} +} + +() => { + const a = R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} + const b = R.assocPath(['a', 'b', 'c'])(42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} + const c = R.assocPath(['a', 'b', 'c'], 42)({a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} +} + +() => { + const a1 = R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}} + // optionally specify return type + const a2 = R.dissocPath<{a :{ b: number}}>(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}} + const a3 = R.dissocPath(['a', 'b', 'c'])({a: {b: {c: 42}}}); //=> {a: {b: {}}} +} + +() => { + var obj1 = [{}, {}, {}]; + var obj2 = [{a:1}, {a:2}, {a:3}]; + const a1: any[] = R.clone(obj1); + const a2: {a: number}[] = R.clone(obj2); + const a3: any = R.clone({}); + const a4: number = R.clone(10); + const a5: string = R.clone('foo'); + const a6: number = R.clone(Date.now()); +} + +() => { + var o1 = { a: 1, b: 2, c: 3, d: 4 }; + var o2 = { a: 10, b: 20, c: 3, d: 40 }; + const a1 = R.eqProps('a', o1, o2); //=> false + const a2 = R.eqProps('c', o1, o2); //=> true + const a3: {(obj1: T, obj2: U): boolean} = R.eqProps('c'); + const a4: {(obj2: U): boolean} = R.eqProps('c', o1); +} + +() => { + const a1 = R.evolve({ elapsed: R.add(1), remaining: R.add(-1) }, { name: 'Tomato', elapsed: 100, remaining: 1400 }); + const a2 = R.evolve({ elapsed: R.add(1), remaining: R.add(-1) })({ name: 'Tomato', elapsed: 100, remaining: 1400 }); +} + +() => { + // var tomato = {firstName: 'Tomato ', data: {elapsed: 100, remaining: 1400}, id:123}; + // var transformations = { + // firstName: R.trim, + // lastName: R.trim, // Will not get invoked. + // data: {elapsed: R.add(1), remaining: R.add(-1)} + // }; + // const a = R.evolve(transformations, tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123} + // const b = R.evolve(transformations)(tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123} +} + +() => { + const hasName = R.has('name'); + const a1: boolean = hasName({name: 'alice'}); //=> true + const a2: boolean = hasName({name: 'bob'}); //=> true + const a3: boolean = hasName({}); //=> false + + const point = {x: 0, y: 0}; + const pointHas = R.flip(R.has)(point); + const b1: boolean = pointHas('x'); //=> true + const b2: boolean = pointHas('y'); //=> true + const b3: boolean = pointHas('z'); //=> false +} + +class Rectangle { + constructor(public width: number, public height: number) { + this.width = width; + this.height = height; + } + area():number { + return this.width * this.height; + } +}; +() => { + + var square = new Rectangle(2, 2); + R.hasIn('width', square); //=> true + R.hasIn('area', square); //=> true + R.flip(R.hasIn)(square)('area'); //=> true +} + +() => { + var raceResultsByFirstName = { + first: 'alice', + second: 'jake', + third: 'alice', + }; + R.invert(raceResultsByFirstName); + //=> { 'alice': ['first', 'third'], 'jake':['second'] } +} + +() => { + let raceResults0 = { + first: 'alice', + second: 'jake' + }; + R.invertObj(raceResults0); + //=> { 'alice': 'first', 'jake':'second' } + + // Alternatively: + let raceResults1 = ['alice', 'jake']; + R.invertObj(raceResults1); + //=> { 'alice': '0', 'jake':'1' } +} + +() => { + R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] +} + +() => { + var f = new F(); + R.keysIn(f); //=> ['x', 'y'] +} + +() => { + var xLens = R.lens(R.prop('x'), R.assoc('x')); + R.view(xLens, {x: 1, y: 2}); //=> 1 + R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} + R.set(xLens)(4, {x: 1, y: 2}); //=> {x: 4, y: 2} + R.set(xLens, 4)({x: 1, y: 2}); //=> {x: 4, y: 2} + R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} + R.over(xLens, R.negate)({x: 1, y: 2}); //=> {x: -1, y: 2} + R.over(xLens)(R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} +} +() => { + var headLens = R.lensIndex(0); + R.view(headLens, ['a', 'b', 'c']); //=> 'a' + R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c'] + R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c'] +} +() => { + var xLens = R.lensProp('x'); + R.view(xLens, {x: 1, y: 2}); //=> 1 + R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} + R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} +} + +() => { + const xyLens = R.lensPath(['x', 'y']); + + R.view(xyLens, {x: {y: 2, z: 3}}); //=> 2 + R.set(xyLens, 4, {x: {y: 2, z: 3}}); //=> {x: {y: 4, z: 3}} + R.over(xyLens, R.negate, {x: {y: 2, z: 3}}); //=> {x: {y: -2, z: 3}} +} + +() => { + R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] +} + +() => { + var f = new F(); + R.keysIn(f); //=> ['x', 'y'] +} + +() => { + var headLens = R.lens( + function get(arr: number[]) { return arr[0]; }, + function set(val: number, arr: number[]) { return [val].concat(arr.slice(1)); } + ); + headLens([10, 20, 30, 40]); //=> 10 + headLens.set('mu', [10, 20, 30, 40]); //=> ['mu', 20, 30, 40] + + var phraseLens = R.lens( + function get(obj: any) { return obj.phrase; }, + function set(val: string, obj: any) { + var out = R.clone(obj); + out.phrase = val; + return out; + } + ); + var obj1 = { phrase: 'Absolute filth . . . and I LOVED it!'}; + var obj2 = { phrase: "What's all this, then?"}; + phraseLens(obj1); // => 'Absolute filth . . . and I LOVED it!' + phraseLens(obj2); // => "What's all this, then?" + phraseLens.set('Ooh Betty', obj1); //=> { phrase: 'Ooh Betty'} +} + + +() => { + var phraseLens = R.lensProp('phrase'); + var obj1 = { phrase: 'Absolute filth . . . and I LOVED it!'}; + var obj2 = { phrase: "What's all this, then?"}; + phraseLens(obj1); // => 'Absolute filth . . . and I LOVED it!' + phraseLens(obj2); // => "What's all this, then?" + phraseLens.set('Ooh Betty', obj1); //=> { phrase: 'Ooh Betty'} +} + +() => { + R.merge({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); + //=> { 'name': 'fred', 'age': 40 } + + var resetToDefault = R.flip(R.merge)({x: 0}); + resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2} +} + +() => { + const a = R.mergeAll([{foo:1},{bar:2},{baz:3}]); //=> {foo:1,bar:2,baz:3} + const b = R.mergeAll([{foo:1},{foo:2},{bar:2}]); //=> {foo:2,bar:2} +} + +() => { + const a = R.mergeWith(R.concat, + { a: true, values: [10, 20] }, + { b: true, values: [15, 35] }); + //=> { a: true, b: true, values: [10, 20, 15, 35] } +} + +() => { + let concatValues = (k:string, l: string, r: string) => k == 'values' ? R.concat(l, r) : r; + R.mergeWithKey(concatValues, + { a: true, thing: 'foo', values: [10, 20] }, + { b: true, thing: 'bar', values: [15, 35] }); + const merge = R.mergeWithKey(concatValues); + merge({ a: true, thing: 'foo', values: [10, 20] }, { b: true, thing: 'bar', values: [15, 35] }); +} + +() => { + const a1 = R.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2 + const a2 = R.pathOr('N/A', ['a', 'b'])({a: {b: 2}}); //=> 2 + const a3 = R.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A" + const a4 = R.pathOr({c:2})(['a', 'b'], {c: {b: 2}}); //=> "N/A" +} + +() => { + var isPositive = function(n: number) { + return n > 0; + }; + const a1 = R.pickBy(isPositive, {a: 1, b: 2, c: -1, d: 0, e: 5}); //=> {a: 1, b: 2, e: 5} + var containsBackground = function(val: any) { + return val.bgcolor; + }; + var colors = {1: {color: 'read'}, 2: {color: 'black', bgcolor: 'yellow'}}; + R.pickBy(containsBackground, colors); //=> {2: {color: 'black', bgcolor: 'yellow'}} + + var isUpperCase = function(val: number, key: string) { return key.toUpperCase() === key; } + R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4} +} + + +() => { + const a1 = R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + const a2 = R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1} + const a3 = R.pick(['a', 'e', 'f'])({a: 1, b: 2, c: 3, d: 4}); //=> {a: 1} + const a4 = R.pick(['a', 'e', 'f'], [1, 2, 3, 4]); //=> {a: 1} +} + +() => { + var matchPhrases = R.compose( + R.objOf('must'), + R.map(R.objOf('match_phrase')) +) + +matchPhrases(['foo', 'bar', 'baz']); +} +() => { + R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3} + R.omit(['a', 'd'])({a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3} +} + + +() => { + R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3} +} + +() => { + R.pair('foo', 'bar'); //=> ['foo', 'bar'] + let p = R.pair('foo', 1); //=> ['foo', 'bar'] + let x: string = p[0]; + let y: number = p[1]; +} + +() => { + var headLens = R.lensIndex(0); + R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']); //=> ['FOO', 'bar', 'baz'] +} + +() => { + R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + R.pickAll(['a', 'd'])({a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined} + R.pickAll(['a', 'e', 'f'])({a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined} +} + +() => { + var isUpperCase = function(val: number, key: string) { return key.toUpperCase() === key; } + R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4} +} + +() => { + var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2}; + var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7}; + var kids = [abby, fred]; + R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}] +} + +() => { + var x: number = R.prop('x', {x: 100}); //=> 100 + const a = R.prop('x', {}); //=> undefined +} + +() => { + var alice = { + name: 'ALICE', + age: 101 + }; + var favorite = R.prop('favoriteLibrary'); + var favoriteWithDefault = R.propOr('Ramda', 'favoriteLibrary'); + + const s1 = favorite(alice); //=> undefined + const s2 = favoriteWithDefault(alice); //=> 'Ramda' +} + +() => { + const a: boolean = R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true + const b: boolean = R.propSatisfies(x => x > 0, 'x')({x: 1, y: 2}); //=> true + const c: boolean = R.propSatisfies(x => x > 0)('x')({x: 1, y: 2}); //=> true +} + +() => { + R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2] + R.props(['c', 'a', 'b'], {b: 2, a: 1}); //=> [undefined, 1, 2] + + var fullName = R.compose(R.join(' '), R.props(['first', 'last'])); + fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth' +} + +() => { + const a = R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]] +} + +() => { + var f = new F(); + const a1 = R.toPairsIn(f); //=> [['x','X'], ['y','Y']] + const a2 = R.toPairsIn(f); //=> [['x','X'], ['y','Y']] +} + +() => { + const a = R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3] +} +() => { + var f = new F(); + const a = R.valuesIn(f); //=> ['X', 'Y'] +} + +() => { + var spec = {x: 2}; + var x1: boolean = R.where(spec, {w: 10, x: 2, y: 300}); //=> true + var x2: boolean = R.where(spec, {x: 1, y: 'moo', z: true}); //=> false + var x3: boolean = R.where(spec)({w: 10, x: 2, y: 300}); //=> true + var x4: boolean = R.where(spec)({x: 1, y: 'moo', z: true}); //=> false + + // There's no way to represent the below functionality in typescript + // per http://stackoverflow.com/a/29803848/632495 + // will need a work around. + + var spec2 = {x: function(val: number, obj: any) { return val + obj.y > 10; }}; + R.where(spec2, {x: 2, y: 7}); //=> false + R.where(spec2, {x: 3, y: 8}); //=> true + + var xs = [{x: 2, y: 1}, {x: 10, y: 2}, {x: 8, y: 3}, {x: 10, y: 4}]; + R.filter(R.where({x: 10}), xs); // ==> [{x: 10, y: 2}, {x: 10, y: 4}] + R.filter(R.where({x: 10}))(xs); // ==> [{x: 10, y: 2}, {x: 10, y: 4}] +} + +() => { + // pred :: Object -> Boolean + var pred = R.whereEq({a: 1, b: 2}); + pred({a: 1}); //=> false + pred({a: 1, b: 2}); //=> true + pred({a: 1, b: 2, c: 3}); //=> true + pred({a: 1, b: 1}); //=> false + R.whereEq({a: 'one'}, {a: 'one'}); // => true +} + +() => { + const a: number[] = R.without([1, 2], [1, 2, 1, 3, 4]); //=> [3, 4] +} + +() => { + var mapIndexed = R.addIndex(R.map); + mapIndexed(function(val: string, idx: number) {return idx + '-' + val;})(['f', 'o', 'o', 'b', 'a', 'r']); + //=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r'] + mapIndexed((rectangle: Rectangle, idx: number):number => rectangle.area()*idx, [new Rectangle(1,2), new Rectangle(4,7)]); + //=> [2, 56] +} + +() => { + var reduceIndexed = R.addIndex(R.reduce); + reduceIndexed(function(acc: string, val: string, idx: number) { + return acc + ',' + idx + '-' + val; + } + ,'' + ,['f', 'o', 'o', 'b', 'a', 'r']); + //=> ['0-f,1-o,2-o,3-b,4-a,5-r'] +} + + + +() => { + var t = R.always('Tee'); + const x: string = t(); //=> 'Tee' +} + +() => { + const x: number[] = R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6] + const y: number[] = R.ap([R.multiply(2), R.add(3)])([1,2,3]); //=> [2, 4, 6, 4, 5, 6] +} + +() => { + var nums = [1, 2, 3, -99, 42, 6, 7]; + R.apply(Math.max, nums); //=> 42 + R.apply(Math.max)(nums); //=> 42 +} + +() => { + type T = {sum: number, nested: {mul: number}}; + const getMetrics = R.applySpec({ + sum: R.add, nested: { mul: R.multiply } + }); + const result = getMetrics(2, 4); // => { sum: 6, nested: { mul: 8 } } +} + +() => { + var takesThreeArgs = function(a: number, b: number, c: number) { + return [a, b, c]; + }; + takesThreeArgs.length; //=> 3 + takesThreeArgs(1, 2, 3); //=> [1, 2, 3] + + var takesTwoArgs = R.binary(takesThreeArgs); + takesTwoArgs.length; //=> 2 + // Only 2 arguments are passed to the wrapped function + takesTwoArgs(1, 2, 3); //=> [1, 2, undefined] +} + +() => { + var indentN = R.pipe(R.times(R.always(' ')), + R.join(''), + R.replace(/^(?!$)/gm) + ); + + var format = R.converge( + R.call, [ + R.pipe(R.prop('indent'), indentN), + R.prop('value') + ] + ); + + format({indent: 2, value: 'foo\nbar\nbaz\n'}); //=> ' foo\n bar\n baz\n' +} + +() => { + type T = {age: number}; + var cmp = R.comparator(function(a: T, b: T) { + return a.age < b.age; + }); + var people = [ + {name: 'Agy', age:33}, {name: 'Bib', age: 15}, {name: 'Cari', age: 16} + ]; + R.sort(cmp, people); +} + +() => { + var add = function(a: number, b: number) { return a + b; }; + var multiply = function(a: number, b: number) { return a * b; }; + var subtract = function(a: number, b: number) { return a - b; }; + + //≅ multiply( add(1, 2), subtract(1, 2) ); + const x: number = R.converge(multiply, [ add, subtract ])(1, 2); //=> -3 + + var add3 = function(a: number, b: number, c: number) { return a + b + c; }; + const y: number = R.converge(add3, [ multiply, add, subtract ])(1, 2); //=> 4 +} + +() => { + const f0 = R.compose(Math.pow); + const f1 = R.compose(R.negate, Math.pow); + const f2 = R.compose(R.inc, R.negate, Math.pow); + const f3 = R.compose(R.inc, R.inc, R.negate, Math.pow); + const f4 = R.compose(R.inc, R.inc, R.inc, R.negate, Math.pow); + const f5 = R.compose(R.inc, R.inc, R.inc, R.inc, R.negate, Math.pow); + const x0: number = f0(3, 4); // -(3^4) + 1 + const x1: number = f1(3, 4); // -(3^4) + 1 + const x2: number = f2(3, 4); // -(3^4) + 1 + const x3: number = f3(3, 4); // -(3^4) + 1 + const x4: number = f4(3, 4); // -(3^4) + 1 + const x5: number = f5(3, 4); // -(3^4) + 1 +} + +() => { + const fn = function(a: string, b: number, c: string) { + return [a,b,c]; + } + const gn = R.compose(R.length, fn); + const x: number = gn('Hello', 4, "world"); +} + +(() => { + var Circle = function(r: number) { + this.r = r; + this.colors = Array.prototype.slice.call(arguments, 1); + }; + Circle.prototype.area = function() {return Math.PI * Math.pow(this.r, 2);}; + var circleN = R.constructN(2, Circle); + var c1 = circleN(1, 'red'); + var circle = R.construct(Circle); + var c1 = circle(1, 'red'); +})(); + +/***************************************************************** + * Relation category + */ + +() => { + var numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2]; + var letters = R.split('', 'abcABCaaaBBc'); + R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1} + R.countBy(R.toLower)(letters); //=> {'a': 5, 'b': 4, 'c': 3} +} + +() => { + R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2] + R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5] +} + +() => { + function cmp(x: any, y: any) { return x.a === y.a; } + var l1 = [{a: 1}, {a: 2}, {a: 3}]; + var l2 = [{a: 3}, {a: 4}]; + R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}] +} + +() => { + R.equals(1, 1); //=> true + R.equals('2', '1'); //=> false + R.equals([1, 2, 3], [1, 2, 3]); //=> true + + var a: any = {}; a.v = a; + var b: any = {}; b.v = b; + R.equals(a, b); //=> true +} + +() => { + const a1 = R.identity(1); //=> 1 + let obj = {}; + const a2 = R.identity([1,2,3]); + const a3 = R.identity(['a','b','c']); + const a4 = R.identity(obj) === obj; //=> true +} + +() => { + var o = {}; + R.identical(o, o); //=> true + R.identical(1, 1); //=> true + R.identical('2', '1'); //=> false + R.identical([], []); //=> false + R.identical(0, -0); //=> false + R.identical(NaN, NaN); //=> true +} + +() => { + R.path(['a', 'b'], {a: {b: 2}}); //=> 2 + R.path(['a', 'b'])({a: {b: 2}}); //=> 2 +} + +() => { + var sortByNameCaseInsensitive = R.sortBy(R.compose(R.toLower, R.prop('name'))); + var alice = { + name: 'ALICE', + age: 101 + }; + var bob = { + name: 'Bob', + age: -10 + }; + var clara = { + name: 'clara', + age: 314.159 + }; + var people = [clara, bob, alice]; + sortByNameCaseInsensitive(people); //=> [alice, bob, clara] +} + +() => { + const a: number[][] = R.splitAt(1, [1, 2, 3]); //=> [[1], [2, 3]] + const b: number[][] = R.splitAt(1)([1, 2, 3]); //=> [[1], [2, 3]] + const c: string[] = R.splitAt(5, 'hello world'); //=> ['hello', ' world'] + const d: string[] = R.splitAt(-1, 'foobar'); //=> ['fooba', 'r'] +} + +() => { + const a: number[][] = R.splitWhen(R.equals(2), [1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]] + const b: number[][] = R.splitWhen(R.equals(2))([1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]] +} + +() => { + R.add(2, 3); //=> 5 + R.add(7)(10); //=> 17 + R.add("Hello", " World"); //=> "Hello World" + R.add("Hello")(" World"); //=> "Hello World" +} + +() => { + R.dec(42); //=> 41 +} + +() => { + R.divide(71, 100); //=> 0.71 + + var half = R.flip(R.divide)(2); + half(42); //=> 21 + + var reciprocal = R.divide(1); + reciprocal(4); //=> 0.25 +} + +() => { + R.gt(2, 6); //=> false + R.gt(2, 0); //=> true + R.gt(2, 2); //=> false + R.flip(R.gt)(2)(10); //=> true + R.gt(2)(10); //=> false +} + +() => { + R.gte(2, 6); //=> false + R.gte(2, 0); //=> true + R.gte(2, 2); //=> false + R.flip(R.gte)(2)(10); //=> true + R.gte(2)(10); //=> false +} + +() => { + R.isNaN(NaN); //=> true + R.isNaN(undefined); //=> false + R.isNaN({}); //=> false +} + +() => { + R.lt(2, 6); //=> true + R.lt(2, 0); //=> false + R.lt(2, 2); //=> false + R.lt(5)(10); //=> true + R.flip(R.lt)(5)(10); //=> false // right-sectioned currying +} + +() => { + R.lte(2, 6); //=> true + R.lte(2, 0); //=> false + R.lte(2, 2); //=> true + R.flip(R.lte)(2)(1); //=> true + R.lte(2)(10); //=> true +} + +() => { + R.mathMod(-17, 5); //=> 3 + R.mathMod(17, 5); //=> 2 + R.mathMod(17, -5); //=> NaN + R.mathMod(17, 0); //=> NaN + R.mathMod(17.2, 5); //=> NaN + R.mathMod(17, 5.3); //=> NaN + + var clock = R.flip(R.mathMod)(12); + clock(15); //=> 3 + clock(24); //=> 0 + + var seventeenMod = R.mathMod(17); + seventeenMod(3); //=> 2 +} + +() => { + var hasName = R.has('name'); + hasName({name: 'alice'}); //=> true + hasName({name: 'bob'}); //=> true + hasName({}); //=> false + + var point = {x: 0, y: 0}; + var pointHas = R.flip(R.has)(point); + pointHas('x'); //=> true + pointHas('y'); //=> true + pointHas('z'); //=> false +} + +() => { + let x: R.Ord = R.max(7, 3); //=> 7 + let y: R.Ord = R.max('a', 'z'); //=> 'z' +} + +() => { + function cmp(obj: { x: R.Ord }) { return obj.x; } + var a = {x: 1}, b = {x: 2}, c = {x: 3}, d = {x: "a"}, e = {x:"z"}; + R.maxBy(cmp, a, c); //=> {x: 3} + R.maxBy(cmp)(a, c); //=> {x: 3} + R.maxBy(cmp)(a)(b); + R.maxBy(cmp)(d)(e); +} + +() => { + const a: number = R.mean([2, 7, 9]); //=> 6 + const b: number = R.mean([]); //=> NaN +} + +() => { + const a: number = R.median([7, 2, 10, 9]); //=> 8 + const b: number = R.median([]); //=> NaN +} + +() => { + let x: R.Ord = R.min(9, 3); //=> 3 + let y: R.Ord = R.min('a', 'z'); //=> 'a' +} + +() => { + function cmp(obj: {x: R.Ord}) { return obj.x; } + var a = {x: 1}, b = {x: 2}, c = {x: 3}, d = {x: "a"}, e = {x: "z"}; + R.minBy(cmp, a, b); //=> {x: 1} + R.minBy(cmp)(a, b); //=> {x: 1} + R.minBy(cmp)(a)(c); + R.minBy(cmp, d, e); +} + +() => { + R.modulo(17, 3); //=> 2 + // JS behavior: + R.modulo(-17, 3); //=> -2 + R.modulo(17, -3); //=> 2 + + var isOdd = R.flip(R.modulo)(2); + isOdd(42); //=> 0 + isOdd(21); //=> 1 +} + +() => { + var double = R.multiply(2); + var triple = R.multiply(3); + double(3); //=> 6 + triple(4); //=> 12 + R.multiply(2, 5); //=> 10 +} + +() => { + R.negate(42); //=> -42 +} + +() => { + R.product([2,4,6,8,100,1]); //=> 38400 +} + +() => { + R.subtract(10, 8); //=> 2 + + var minus5 = R.flip(R.subtract)(5); + minus5(17); //=> 12 + + var complementaryAngle = R.subtract(90); + complementaryAngle(30); //=> 60 + complementaryAngle(72); //=> 18 +} + +() => { + R.sum([2,4,6,8,100,1]); //=> 121 +} + +() => { + const a: number[] = R.symmetricDifference([1,2,3,4], [7,6,5,4,3]); //=> [1,2,7,6,5] + const b: number[] = R.symmetricDifference([7,6,5,4,3])([1,2,3,4]); //=> [7,6,5,1,2] +} + +() => { + const eqA = R.eqBy(R.prop('a')); + const l1 = [{a: 1}, {a: 2}, {a: 3}, {a: 4}]; + const l2 = [{a: 3}, {a: 4}, {a: 5}, {a: 6}]; + R.symmetricDifferenceWith(eqA, l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] + R.symmetricDifferenceWith(eqA)(l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] + const c: (a: any[]) => any[] = R.symmetricDifferenceWith(eqA)(l1); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] +} + +/***************************************************************** + * String category + */ + +() => { + R.replace('foo', 'bar', 'foo foo foo'); //=> 'bar foo foo' + R.replace('foo', 'bar')('foo foo foo'); //=> 'bar foo foo' + R.replace('foo')('bar')('foo foo foo'); //=> 'bar foo foo' + R.replace(/foo/, 'bar', 'foo foo foo'); //=> 'bar foo foo' + + // Use the "g" (global) flag to replace all occurrences: + R.replace(/foo/g, 'bar', 'foo foo foo'); //=> 'bar bar bar' + R.replace(/foo/g, 'bar')('foo foo foo'); //=> 'bar bar bar' + R.replace(/foo/g)('bar')('foo foo foo'); //=> 'bar bar bar' +} + +/***************************************************************** + * Is category + */ + +() => { + R.is(Object, {}); //=> true + R.is(Object)({}); //=> true + R.is(Number, 1); //=> true + R.is(Number)(1); //=> true + R.is(Object, 1); //=> false + R.is(Object)(1); //=> false + R.is(String, 's'); //=> true + R.is(String)('s'); //=> true + R.is(String, new String('')); //=> true + R.is(String)(new String('')); //=> true + R.is(Object, new String('')); //=> true + R.is(Object)(new String('')); //=> true + R.is(Object, 's'); //=> false + R.is(Object)('s'); //=> false + R.is(Number, {}); //=> false + R.is(Number)({}); //=> false +} + +/***************************************************************** + * Logic category + */ +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0}; + var f = R.allPass([gt10, even]); + f(11); //=> false + f(12); //=> true +} + +() => { + R.and(false, true); //=> false + R.and(0, []); //=> 0 + R.and(0)([]); //=> 0 + R.and(null, ''); //=> null + var Why: any = (function(val: boolean) { + var why: any; + why.val = val; + why.and = function(x: boolean) { + return this.val && x; + } + return Why; + })(true); + var why = new Why(true); + R.and(why, false); // false +} +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0}; + var f = R.anyPass([gt10, even]); + f(11); //=> true + f(8); //=> true + f(9); //=> false +} + +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0 }; + var f = R.both(gt10, even); + var g = R.both(gt10)(even); + f(100); //=> true + f(101); //=> false +} +() => { + var isEven = function(n: number) { return n % 2 === 0; }; + var isOdd = R.complement(isEven); + isOdd(21); //=> true + isOdd(42); //=> false +} + +(() => { + R.eqBy(Math.abs, 5, -5); //=> true +}); + +() => { + var defaultTo42 = R.defaultTo(42); + defaultTo42(null); //=> 42 + defaultTo42(undefined); //=> 42 + defaultTo42('Ramda'); //=> 'Ramda' +} +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0 }; + var f = R.either(gt10, even); + var g = R.either(gt10)(even); + f(101); //=> true + f(8); //=> true +} +() => { + // Flatten all arrays in the list but leave other values alone. + var flattenArrays = R.map(R.ifElse(Array.isArray, R.flatten, R.identity)); + + flattenArrays([[0], [[10], [8]], 1234, {}]); //=> [[0], [10, 8], 1234, {}] + flattenArrays([[[10], 123], [8, [10]], "hello"]); //=> [[10, 123], [8, 10], "hello"] +} +() => { + R.isEmpty([1, 2, 3]); //=> false + R.isEmpty([]); //=> true + R.isEmpty(''); //=> true + R.isEmpty(null); //=> false + R.isEmpty({}); //=>true + R.isEmpty({a:1}); //=> false +} + +() => { + R.not(true); //=> false + R.not(false); //=> true + R.not(0); // => true + R.not(1); // => false +} + +class Why { + val: boolean; + constructor(val: boolean) { + this.val = val; + } + or(x: boolean) { + return this.val && x; + } +} +() => { + const x0: boolean = R.or(false, true); //=> false + const x1: number|any[] = R.or(0, []); //=> [] + const x2: number|any[] = R.or(0)([]); //=> [] + const x3: string = R.or(null, ''); //=> '' + + var why = new Why(true); + why.or(true) + const x4: Why|boolean = R.or(why, false); // false +} + +() => { + R.intersperse(',', ['foo', 'bar']); //=> ['foo', ',', 'bar'] + R.intersperse(0, [1, 2]); //=> [1, 0, 2] + R.intersperse(0, [1]); //=> [1] +} diff --git a/ramda/ramda.d.ts b/ramda/ramda.d.ts new file mode 100644 index 0000000000..ffa11ca2cb --- /dev/null +++ b/ramda/ramda.d.ts @@ -0,0 +1,1807 @@ +// Type definitions for ramda (www.ramdajs.com) v0.21.0 +// Project: https://github.com/donnut/typescript-ramda +// Definitions by: Erwin Poeze +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var R: R.Static; + +declare namespace R { + type Ord = number | string | boolean; + + interface ListIterator { + (value: T, index: number, list: T[]): TResult; + } + + interface Functor { + map(a: any): T; + } + + interface ObjectIterator { + (element: T, key: string, obj: Dictionary): Dictionary; + } + + interface KeyValuePair extends Array { 0 : K; 1 : V; } + + interface ArrayLike { + nodeType: number; + } + + interface Arity0Fn { + (): any + } + + interface Arity1Fn { + (a: any): any + } + + interface Arity2Fn { + (a: any, b: any): any + } + + interface ObjFunc { + [index:string]: Function; + } + + interface ObjFunc2 { + [index:string]: (x: any, y: any) => boolean; + } + + interface Pred { + (...a: any[]): boolean; + } + + interface ObjPred { + (value: any, key: string): boolean; + } + + interface Dictionary { + [index: string]: T; + } + + interface CharList extends String { + push(x: string): void; + } + + interface Nested { + [index: string]: Nested|{(value: any): U}; + } + + interface Lens { + (obj: T): U; + set(str: string, obj: T): U; + } + + // @see https://gist.github.com/donnut/fd56232da58d25ceecf1, comment by @albrow + interface CurriedFunction2 { + (t1: T1): (t2: T2) => R; + (t1: T1, t2: T2): R; + } + + interface CurriedFunction3 { + (t1: T1): CurriedFunction2; + (t1: T1, t2: T2): (t3: T3) => R; + (t1: T1, t2: T2, t3: T3): R; + } + + interface CurriedFunction4 { + (t1: T1): CurriedFunction3; + (t1: T1, t2: T2): CurriedFunction2; + (t1: T1, t2: T2, t3: T3): (t4: T4) => R; + (t1: T1, t2: T2, t3: T3, t4: T4): R; + } + + interface CurriedFunction5 { + (t1: T1): CurriedFunction4; + (t1: T1, t2: T2): CurriedFunction3; + (t1: T1, t2: T2, t3: T3): CurriedFunction2; + (t1: T1, t2: T2, t3: T3, t4: T4): (t5: T5) => R; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): R; + } + + interface CurriedFunction6 { + (t1: T1): CurriedFunction5; + (t1: T1, t2: T2): CurriedFunction4; + (t1: T1, t2: T2, t3: T3): CurriedFunction3; + (t1: T1, t2: T2, t3: T3, t4: T4): CurriedFunction2; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): (t6: T6) => R; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6): R; + } + + interface Reduced {} + + interface Static { + + /** + * Adds two numbers (or strings). Equivalent to a + b but curried. + */ + add(a: number, b: number): number; + add(a: string, b: string): string; + add(a: number): (b: number) => number; + add(a: string): (b: string) => string; + + /** + * Creates a new list iteration function from an existing one by adding two new parameters to its callback + * function: the current index, and the entire list. + */ + addIndex(fn: (f: (item: T) => U, list: T[]) => U[] ) + : CurriedFunction2<(item: T, idx: number, list?: T[]) => U, T[], U[]>; + /* Special case for forEach */ + addIndex(fn: (f: (item: T) => void, list: T[]) => T[]) + : CurriedFunction2<(item: T, idx: number, list?: T[]) => void, T[], T[]>; + /* Special case for reduce */ + addIndex(fn: (f: (acc:U, item: T) => U, aci:U, list: T[]) => U) + : CurriedFunction3<(acc:U, item: T, idx: number, list?: T[]) => U, U, T[], U>; + + /** + * Applies a function to the value at the given index of an array, returning a new copy of the array with the + * element at the given index replaced with the result of the function application. + */ + adjust(fn: (a: T) => T, index: number, list: T[]): T[]; + adjust(fn: (a: T) => T, index: number): (list: T[]) => T[]; + + /** + * Returns true if all elements of the list match the predicate, false if there are any that don't. + */ + all(fn: (a: T) => boolean, list: T[]): boolean; + all(fn: (a: T) => boolean): (list: T[]) => boolean; + + /** + * Given a list of predicates, returns a new predicate that will be true exactly when all of them are. + */ + allPass(preds: Pred[]): Pred; + + /** + * Returns a function that always returns the given value. + */ + always(val: T): () => T; + + + /** + * A function that returns the first argument if it's falsy otherwise the second argument. Note that this is + * NOT short-circuited, meaning that if expressions are passed they are both evaluated. + */ + and(fn1: T, val2: boolean|any): boolean; + and(fn1: T): (val2: boolean|any) => boolean; + + /** + * Returns true if at least one of elements of the list match the predicate, false otherwise. + */ + any(fn: (a: T) => boolean, list: T[]): boolean; + any(fn: (a: T) => boolean): (list: T[]) => boolean; + + /** + * Given a list of predicates returns a new predicate that will be true exactly when any one of them is. + */ + anyPass(preds: Pred[]): Pred; + + /** + * ap applies a list of functions to a list of values. + */ + ap(fns: ((a: T) => U)[], vs: T[]): U[]; + ap(fns: ((a: T) => U)[]): (vs: T[]) => U[]; + + + /** + * Returns a new list, composed of n-tuples of consecutive elements If n is greater than the length of the list, + * an empty list is returned. + */ + aperture(n: number, list: T): T[][]; + aperture(n: number): (list: T) => T[][]; + + /** + * Returns a new list containing the contents of the given list, followed by the given element. + */ + append(el: U, list: T[]): (T & U)[]; + append(el: U): (list: T[]) => (T & U)[]; + append(el: U): (list: T[]) => (T & U)[]; + + /** + * Applies function fn to the argument list args. This is useful for creating a fixed-arity function from + * a variadic function. fn should be a bound function if context is significant. + */ + apply(fn: (arg0: T, ...args: T[]) => TResult, args: U[]): TResult; + apply(fn: (arg0: T, ...args: T[]) => TResult): (args: U[]) => TResult; + + /** + * Given a spec object recursively mapping properties to functions, creates a function producing an object + * of the same structure, by mapping each property to the result of calling its associated function with + * the supplied arguments. + */ + applySpec(obj: any): (...args: any[]) => T; + + /** + * Makes a shallow clone of an object, setting or overriding the specified property with the given value. + */ + assoc(prop: string, val: T, obj: U): {prop: T} & U; + assoc(prop: string): (val: T, obj: U) => {prop: T} & U; + assoc(prop: string, val: T): (obj: U) => {prop: T} & U; + + + /** + * Makes a shallow clone of an object, setting or overriding the nodes required to create the given path, and + * placing the specific value at the tail end of that path. + */ + assocPath(path: string[], val: T, obj: U): U; + assocPath(path: string[]): (val: T, obj: U) => U; + assocPath(path: string[], val: T): (obj: U) => U; + + /** + * Wraps a function of any arity (including nullary) in a function that accepts exactly 2 + * parameters. Any extraneous parameters will not be passed to the supplied function. + */ + binary(fn: (...args: any[]) => any): Function; + + /** + * Creates a function that is bound to a context. Note: R.bind does not provide the additional argument-binding + * capabilities of Function.prototype.bind. + */ + bind(thisObj: T, fn: (...args: any[]) => any): (...args: any[]) => any; + + + /** + * A function wrapping calls to the two functions in an && operation, returning the result of the first function + * if it is false-y and the result of the second function otherwise. Note that this is short-circuited, meaning + * that the second function will not be invoked if the first returns a false-y value. + */ + both(pred1: Pred, pred2: Pred): Pred; + both(pred1: Pred): (pred2: Pred) => Pred; + + /** + * Returns the result of calling its first argument with the remaining arguments. This is occasionally useful + * as a converging function for R.converge: the left branch can produce a function while the right branch + * produces a value to be passed to that function as an argument. + */ + call(fn: (...args: any[])=> (...args: any[]) => any, ...args: any[]): any; + + /** + * `chain` maps a function over a list and concatenates the results. + * This implementation is compatible with the Fantasy-land Chain spec + */ + chain(fn: (n: T) => U[], list: T[]): U[]; + chain(fn: (n: T) => U[]): (list: T[]) => U[]; + + /** + * Restricts a number to be within a range. + * Also works for other ordered types such as Strings and Date + */ + clamp(min: T, max: T, value: T): T; + clamp(min: T, max: T): (value: T) => T; + clamp(min: T): (max: T, value: T) => T; + clamp(min: T): (max: T) => (value: T) => T; + + /** + * Creates a deep copy of the value which may contain (nested) Arrays and Objects, Numbers, Strings, Booleans and Dates. + */ + clone(value: T): T; + clone(value: T[]): T[]; + + /** + * Makes a comparator function out of a function that reports whether the first element is less than the second. + */ + // comparator(pred: (a: any, b: any) => boolean): (x: number, y: number) => number; + comparator(pred: (a: T, b: T) => boolean): (x: T, y: T) => number; + + /** + * Takes a function f and returns a function g such that: + * - applying g to zero or more arguments will give true if applying the same arguments to f gives + * a logical false value; and + * - applying g to zero or more arguments will give false if applying the same arguments to f gives + * a logical true value. + */ + complement(pred: (...args: any[]) => boolean): (...args: any[]) => boolean + + /** + * Performs right-to-left function composition. The rightmost function may have any arity; the remaining + * functions must be unary. + */ + compose(fn0: (x0: V0) => T1): (x0: V0) => T1; + compose(fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T1; + compose(fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T1; + + compose(fn1: (x: T1) => T2, fn0: (x0: V0) => T1): (x0: V0) => T2; + compose(fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T2; + compose(fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T2; + + compose(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T3; + compose(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T3; + compose(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T3; + + compose(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T4; + compose(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T4; + compose(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T4; + + compose(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T5; + compose(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T5; + compose(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T5; + + compose(fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T6; + compose(fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T6; + compose(fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T6; + + /** + * TODO composeK + */ + + /** + * TODO composeP + */ + + + /** + * Returns a new list consisting of the elements of the first list followed by the elements + * of the second. + */ + concat(list1: T[], list2: T[]): T[]; + concat(list1: T[]): (list2: T[]) => T[]; + concat(list1: string, list2: string): string; + concat(list1: string): (list2: string) => string; + + /** + * Returns a function, fn, which encapsulates if/else-if/else logic. R.cond takes a list of [predicate, transform] pairs. + * All of the arguments to fn are applied to each of the predicates in turn until one returns a "truthy" value, at which + * point fn returns the result of applying its arguments to the corresponding transformer. If none of the predicates + * matches, fn returns undefined. + */ + cond(fns: [Pred, Function][]): Function; + + + /** + * Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. + */ + construct(fn: Function): Function; + + + /** + * Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. + * The arity of the function returned is specified to allow using variadic constructor functions. + */ + constructN(n: number, fn: Function): Function; + + + /** + * Returns `true` if the specified item is somewhere in the list, `false` otherwise. + * Equivalent to `indexOf(a)(list) > -1`. Uses strict (`===`) equality checking. + */ + contains(a: string, list: string): boolean; + contains(a: T, list: T[]): boolean; + contains(a: string): (list: string) => boolean; + contains(a: T): (list: T[]) => boolean; + + /** + * Accepts a converging function and a list of branching functions and returns a new + * function. When invoked, this new function is applied to some arguments, each branching + * function is applied to those same arguments. The results of each branching function + * are passed as arguments to the converging function to produce the return value. + */ + converge(after: Function, fns: Function[]): Function; + + /** + * Counts the elements of a list according to how many match each value + * of a key generated by the supplied function. Returns an object + * mapping the keys produced by `fn` to the number of occurrences in + * the list. Note that all keys are coerced to strings because of how + * JavaScript objects work. + */ + countBy(fn: (a: any) => string|number, list: any[]): any; + countBy(fn: (a: any) => string|number): (list: any[]) => any; + + /** + * Returns a curried equivalent of the provided function. The curried function has two unusual capabilities. + * First, its arguments needn't be provided one at a time. + */ + curry(fn: (a: T1, b: T2) => TResult): CurriedFunction2 + curry(fn: (a: T1, b: T2, c: T3) => TResult): CurriedFunction3 + curry(fn: (a: T1, b: T2, c: T3, d: T4) => TResult): CurriedFunction4 + curry(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => TResult): CurriedFunction5 + curry(fn: (a: T1, b: T2, c: T3, d: T4, e: T5, f: T6) => TResult): CurriedFunction6 + curry(fn: Function): Function + + + /** + * Returns a curried equivalent of the provided function, with the specified arity. The curried function has + * two unusual capabilities. First, its arguments needn't be provided one at a time. + */ + curryN(length: number, fn: (...args: any[]) => any): Function; + + + /** + * Decrements its argument. + */ + dec(n: number): number; + + /** + * Returns the second argument if it is not null or undefined. If it is null or undefined, the + * first (default) argument is returned. + */ + defaultTo(a: T, b: U): T|U + defaultTo(a: T): (b: U) => T|U + + /** + * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. + */ + difference(list1: T[], list2: T[]): T[]; + difference(list1: T[]): (list2: T[]) => T[]; + + /** + * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. + * Duplication is determined according to the value returned by applying the supplied predicate to two list + * elements. + */ + differenceWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + + /* + * Returns a new object that does not contain a prop property. + */ + // It seems impossible to infer the return type, so this may to be specified explicitely + dissoc(prop: string, obj: any): T; + dissoc(prop: string): (obj: any) => U; + + /** + * Makes a shallow clone of an object, omitting the property at the given path. + */ + dissocPath(path: string[], obj: any): T; + dissocPath(path: string[]): (obj: any) => T; + + /** + * Divides two numbers. Equivalent to a / b. + */ + divide(a: number, b: number): number; + divide(a: number): (b: number) => number; + + /** + * Returns a new list containing all but the first n elements of the given list. + */ + drop(n: number, xs: T[]): T[]; + drop(n: number, xs: string): string; + drop(n: number): { + (xs: string): string; + (xs: T[]): T[]; + } + + /** + * Returns a list containing all but the last n elements of the given list. + */ + dropLast(n: number, xs: T[]): T[]; + dropLast(n: number, xs: string): string; + dropLast(n: number): { + (xs: T[]): T[]; + (xs: string): string; + } + + /** + * Returns a new list containing all but last then elements of a given list, passing each value from the + * right to the supplied predicate function, skipping elements while the predicate function returns true. + */ + dropLastWhile(fn: (a: T) => boolean, list: T[]): T[]; + dropLastWhile(fn: (a: T) => boolean): (list: T[]) => T[]; + + /** + * Returns a new list containing the last n elements of a given list, passing each value to the supplied + * predicate function, skipping elements while the predicate function returns true. + */ + dropWhile(fn: (a: T) => boolean, list: T[]): T[]; + dropWhile(fn: (a: T) => boolean): (list: T[]) => T[]; + + /** + * A function wrapping calls to the two functions in an || operation, returning the result of the first + * function if it is truth-y and the result of the second function otherwise. Note that this is + * short-circuited, meaning that the second function will not be invoked if the first returns a truth-y value. + */ + either(pred1: Pred, pred2: Pred): Pred; + either(pred1: Pred): (pred2: Pred) => Pred; + + /** + * Returns the empty value of its argument's type. Ramda defines the empty value of Array ([]), Object ({}), + * String (''), and Arguments. Other types are supported if they define .empty and/or .prototype.empty. + * Dispatches to the empty method of the first argument, if present. + */ + empty(x: T): T; + + /** + * Takes a function and two values in its domain and returns true if the values map to the same value in the + * codomain; false otherwise. + */ + eqBy(fn: (a: T) => T, a: T, b: T): boolean; + eqBy(fn: (a: T) => T, a: T): (b: T) => boolean; + eqBy(fn: (a: T) => T): (a: T, b: T) => boolean; + eqBy(fn: (a: T) => T): (a: T) => (b: T) => boolean; + + /** + * Reports whether two functions have the same value for the specified property. + */ + eqProps(prop: string, obj1: T, obj2: U): boolean; + eqProps(prop: string): (obj1: T, obj2: U) => boolean; + eqProps(prop: string, obj1: T): (obj2: U) => boolean; + + /** + * Returns true if its arguments are equivalent, false otherwise. Dispatches to an equals method if present. + * Handles cyclical data structures. + */ + equals(a: T, b: T): boolean; + equals(a: T): (b: T) => boolean; + + /** + * Creates a new object by evolving a shallow copy of object, according to the transformation functions. + */ + evolve(transformations: Nested, obj: V): Nested; + evolve(transformations: Nested): (obj: V) => Nested; + /* + * A function that always returns false. Any passed in parameters are ignored. + */ + F(): boolean; + + /** + * Returns a new list containing only those items that match a given predicate function. The predicate function is passed one argument: (value). + */ + filter(fn: (value: T) => boolean): (list: T[]) => T[]; + filter(fn: (value: T) => boolean, list: T[]): T[]; + + /** + * Returns the first element of the list which matches the predicate, or `undefined` if no + * element matches. + */ + find(fn: (a: T) => boolean, list: T[]): T; + find(fn: (a: T) => boolean): (list: T[]) => T; + + + /** + * Returns the index of the first element of the list which matches the predicate, or `-1` + * if no element matches. + */ + findIndex(fn: (a: T) => boolean, list: T[]): number; + findIndex(fn: (a: T) => boolean): (list: T[]) => number; + + /** + * Returns the last element of the list which matches the predicate, or `undefined` if no + * element matches. + */ + findLast(fn: (a: T) => boolean, list: T[]): T; + findLast(fn: (a: T) => boolean): (list: T[]) => T; + + /** + * Returns the index of the last element of the list which matches the predicate, or + * `-1` if no element matches. + */ + findLastIndex(fn: (a: T) => boolean, list: T[]): number; + findLastIndex(fn: (a: T) => boolean): (list: T[]) => number; + + /** + * Returns a new list by pulling every item out of it (and all its sub-arrays) and putting + * them in a new array, depth-first. + */ + flatten(x: T[][]): T[]; + flatten(x: T[]): T[]; + + /** + * Returns a new function much like the supplied one, except that the first two arguments' + * order is reversed. + */ + flip(fn: (arg0: T, arg1: U) => TResult): (arg1: U, arg0?: T) => TResult; + flip(fn: (arg0: T, arg1: U, ...args: any[]) => TResult): (arg1: U, arg0?: T, ...args: any[]) => TResult; + + + /** + * Iterate over an input list, calling a provided function fn for each element in the list. + */ + forEach(fn: (x: T) => void, list: T[]): T[]; + forEach(fn: (x: T) => void): (list: T[]) => T[]; + + /** + * Creates a new object out of a list key-value pairs. + */ + fromPairs(pairs: KeyValuePair[]): {[index: string]: V}; + fromPairs(pairs: KeyValuePair[]): {[index: number]: V}; + + /** + * Splits a list into sublists stored in an object, based on the result of + * calling a String-returning function + * on each element, and grouping the results according to values returned. + */ + groupBy(fn: (a: T) => string, list: T[]): {[index: string]: T[]} + groupBy(fn: (a: T) => string): (list: T[]) => {[index: string]: T[]} + + /** + * Takes a list and returns a list of lists where each sublist's elements are all "equal" according to the provided equality function + */ + groupWith(fn: (x: T, y: T) => boolean, list: T[]): T[][] + groupWith(fn: (x: T, y: T) => boolean, list: string): string[] + + /** + * Returns true if the first parameter is greater than the second. + */ + gt(a: number, b: number): boolean; + gt(a: number): (b: number) => boolean; + + /** + * Returns true if the first parameter is greater than or equal to the second. + */ + gte(a: number, b: number): boolean; + gte(a: number): (b: number) => boolean; + + /** + * Returns whether or not an object has an own property with the specified name. + */ + has(s: string, obj: T): boolean; + has(s: string): (obj: T) => boolean; + + /** + * Returns whether or not an object or its prototype chain has a property with the specified name + */ + hasIn(s: string, obj: T): boolean; + hasIn(s: string): (obj: T) => boolean; + + /** + * Returns the first element in a list. + * In some libraries this function is named `first`. + */ + head(list: T[]): T; + head(list: string): string; + + /** + * Returns true if its arguments are identical, false otherwise. Values are identical if they reference the + * same memory. NaN is identical to NaN; 0 and -0 are not identical. + */ + identical(a: T, b: T): boolean; + identical(a: T): (b: T) => boolean; + + + /** + * A function that does nothing but return the parameter supplied to it. Good as a default + * or placeholder function. + */ + identity(a: T): T; + + /** + * Creates a function that will process either the onTrue or the onFalse function depending upon the result + * of the condition predicate. + */ + ifElse(fn: Pred, onTrue: Arity1Fn, onFalse: Arity1Fn): Arity1Fn; + + + /** + * Increments its argument. + */ + inc(n: number): number; + + /** + * Given a function that generates a key, turns a list of objects into an object indexing the objects + * by the given key. + */ + indexBy(fn: (a: T) => string, list: T[]): U; + indexBy(fn: (a: T) => string): (list: T[]) => U; + + /** + * Returns the position of the first occurrence of an item in an array + * (by strict equality), + * or -1 if the item is not included in the array. + */ + indexOf(target: T, list: T[]): number; + indexOf(target: T): (list: T[]) => number; + + /** + * Returns all but the last element of a list. + */ + init(list: T[]): T[]; + + /** + * Inserts the supplied element into the list, at index index. Note that + * this is not destructive: it returns a copy of the list with the changes. + */ + insert(index: number, elt: T, list: T[]): T[]; + insert(index: number, elt: T): (list: T[]) => T[]; + insert(index: number): (elt: T, list: T[]) => T[]; + + /** + * Inserts the sub-list into the list, at index `index`. _Note that this + * is not destructive_: it returns a copy of the list with the changes. + */ + insertAll(index: number, elts: T[], list: T[]): T[]; + insertAll(index: number, elts: T[]): (list: T[]) => T[]; + insertAll(index: number): (elts: T[], list: T[]) => T[]; + + + /** + * Combines two lists into a set (i.e. no duplicates) composed of those elements common to both lists. + */ + intersection(list1: T[], list2: T[]): T[]; + + + /** + * Combines two lists into a set (i.e. no duplicates) composed of those + * elements common to both lists. Duplication is determined according + * to the value returned by applying the supplied predicate to two list + * elements. + */ + intersectionWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + + /** + * Creates a new list with the separator interposed between elements. + */ + intersperse(separator: T, list: T[]): T[]; + intersperse(separator: T): (list: T[]) => T[]; + + /** + * Transforms the items of the list with the transducer and appends the transformed items to the accumulator + * using an appropriate iterator function based on the accumulator type. + */ + into(acc: any, xf: Function, list: T[]): T[]; + into(acc: any, xf: Function): (list: T[]) => T[]; + into(acc: any): (xf: Function, list: T[]) => T[]; + + /** + * Same as R.invertObj, however this accounts for objects with duplicate values by putting the values into an array. + */ + invert(obj: T): {[index:string]: string[]}; + + /** + * Returns a new object with the keys of the given object as values, and the values of the given object as keys. + */ + invertObj(obj: any): {[index:string]: string}; + invertObj(obj: {[index: number]: string}): {[index:string]: string}; + + + /** + * Turns a named method of an object (or object prototype) into a function that can be + * called directly. Passing the optional `len` parameter restricts the returned function to + * the initial `len` parameters of the method. + * + * The returned function is curried and accepts `len + 1` parameters (or `method.length + 1` + * when `len` is not specified), and the final parameter is the target object. + */ + invoker(name: string, obj: any, len?: number): Function; + invoker(name: string): (obj: any, len?: number) => Function; + + /** + * See if an object (`val`) is an instance of the supplied constructor. + * This function will check up the inheritance chain, if any. + */ + is(ctor: any, val: any): boolean; + is(ctor: any): (val: any) => boolean; + + /** + * Tests whether or not an object is similar to an array. + */ + isArrayLike(val: any): boolean; + + /** + * Reports whether the list has zero elements. + */ + isEmpty(value: any): boolean; + + + /** + * Returns true if the input value is NaN. + */ + isNaN(x: any): boolean; + + /** + * Checks if the input value is null or undefined. + */ + isNil(value: any): boolean; + + /** + * Returns a string made by inserting the `separator` between each + * element and concatenating all the elements into a single string. + */ + join(x: string, xs: any[]): string; + join(x: string): (xs: any[]) => string; + + /** + * Applies a list of functions to a list of values. + */ + juxt(fns: {(...args: T[]): U}[]): (...args: T[]) => U[]; + + + /** + * Returns a list containing the names of all the enumerable own + * properties of the supplied object. + */ + keys(x: T): string[]; + + /** + * Returns a list containing the names of all the + * properties of the supplied object, including prototype properties. + */ + keysIn(obj: T): string[]; + + /** + * Returns the last element from a list. + */ + last(list: T[]): T; + last(list: string): string; + + /** + * Returns the position of the last occurrence of an item (by strict equality) in + * an array, or -1 if the item is not included in the array. + */ + lastIndexOf(target: T, list: T[]): number; + + /** + * Returns the number of elements in the array by returning list.length. + */ + length(list: any[]): number; + + /** + * Returns a lens for the given getter and setter functions. The getter + * "gets" the value of the focus; the setter "sets" the value of the focus. + * The setter should not mutate the data structure. + */ + lens(getter: (s: T) => U, setter: (a: U, s: T) => V): Lens; + + /** + * Creates a lens that will focus on index n of the source array. + */ + lensIndex(n: number): Lens; + + /** + * Returns a lens whose focus is the specified path. + * See also view, set, over. + */ + lensPath(path: string[]): Lens; + + /** + * lensProp creates a lens that will focus on property k of the source object. + */ + lensProp(str: string): { + (obj: T): U; + set(val: T, obj: U): V; + /*map(fn: Function, obj: T): T*/ + } + + /** + * "lifts" a function of arity > 1 so that it may "map over" a list, Function or other object that satisfies + * the FantasyLand Apply spec. + */ + lift(fn: Function, ...args: any[]): any; + + /** + * "lifts" a function to be the specified arity, so that it may "map over" that many lists, Functions or other + * objects that satisfy the FantasyLand Apply spec. + */ + liftN(n: number, fn: Function, ...args: any[]): any; + + + /** + * Returns true if the first parameter is less than the second. + */ + lt(a: number, b: number): boolean; + lt(a: number): (b: number) => boolean; + + /** + * Returns true if the first parameter is less than or equal to the second. + */ + lte(a: number, b: number): boolean; + lte(a: number): (b: number) => boolean; + + /** + * Returns a new list, constructed by applying the supplied function to every element of the supplied list. + */ + map(fn: (x: T) => U, list: T[]): U[]; + map(fn: (x: T) => U, obj: Functor): Functor; // used in functors + map(fn: (x: T) => U): (list: T[]) => U[]; + + /** + * The mapAccum function behaves like a combination of map and reduce. + */ + mapAccum(fn: (acc: U, value: T) => [U, TResult], acc: U, list: T[]): [U, TResult[]]; + mapAccum(fn: (acc: U, value: T) => [U, TResult]): (acc: U, list: T[]) => [U, TResult[]]; + mapAccum(fn: (acc: U, value: T) => [U, TResult], acc: U): (list: T[]) => [U, TResult[]]; + + /** + * The mapAccumRight function behaves like a combination of map and reduce. + */ + mapAccumRight(fn: (acc: U, value: T) => [U, TResult], acc: U, list: T[]): [U, TResult[]]; + mapAccumRight(fn: (acc: U, value: T) => [U, TResult]): (acc: U, list: T[]) => [U, TResult[]]; + mapAccumRight(fn: (acc: U, value: T) => [U, TResult], acc: U): (list: T[]) => [U, TResult[]]; + + + /** + * Like mapObj, but but passes additional arguments to the predicate function. + */ + mapObjIndexed(fn: (value: T, key: string, obj?: any) => TResult, obj: any): {[index:string]: TResult}; + mapObjIndexed(fn: (value: T, key: string, obj?: any) => TResult): (obj: any) => {[index:string]: TResult}; + + /** + * Tests a regular expression agains a String + */ + match(regexp: RegExp, str: string): any[]; + match(regexp: RegExp): (str: string) => any[]; + + + /** + * mathMod behaves like the modulo operator should mathematically, unlike the `%` + * operator (and by extension, R.modulo). So while "-17 % 5" is -2, + * mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN + * when the modulus is zero or negative. + */ + mathMod(a: number, b: number): number; + mathMod(a: number): (b: number) => number; + + + /** + * Returns the larger of its two arguments. + */ + max(a: Ord, b: Ord): Ord; + max(a: Ord): (b: Ord) => Ord; + + /** + * Takes a function and two values, and returns whichever value produces + * the larger result when passed to the provided function. + */ + maxBy(keyFn: (a: T) => Ord, a: T, b: T): T; + maxBy(keyFn: (a: T) => Ord, a: T): (b: T) => T; + maxBy(keyFn: (a: T) => Ord): CurriedFunction2 + + /** + * Returns the mean of the given list of numbers. + */ + mean(list: number[]): number; + + /** + * Returns the median of the given list of numbers. + */ + median(list: number[]): number; + + /** + * Creates a new function that, when invoked, caches the result of calling fn for a given argument set and + * returns the result. Subsequent calls to the memoized fn with the same argument set will not result in an + * additional call to fn; instead, the cached result for that set of arguments will be returned. + */ + memoize(fn: Function): Function; + + /** + * Create a new object with the own properties of a + * merged with the own properties of object b. + * This function will *not* mutate passed-in objects. + */ + merge(a: T1, b: T2): T1 & T2; + merge(a: T1): (b: T2) => T1 & T2; + + + /** + * Merges a list of objects together into one object. + */ + mergeAll(list: any[]): T; + + /** + * Creates a new object with the own properties of the two provided objects. If a key exists in both objects, + * the provided function is applied to the values associated with the key in each object, with the result being used as + * the value associated with the key in the returned object. The key will be excluded from the returned object if the + * resulting value is undefined. + */ + mergeWith(fn: (x: any, z: any) => any, a: U, b: V): U & V; + mergeWith(fn: (x: any, z: any) => any, a: U): (b: V) => U & V; + mergeWith(fn: (x: any, z: any) => any): (a: U, b: V) => U & V; + + /** + * Creates a new object with the own properties of the two provided objects. If a key exists in both objects, + * the provided function is applied to the key and the values associated with the key in each object, with the + * result being used as the value associated with the key in the returned object. The key will be excluded from + * the returned object if the resulting value is undefined. + */ + mergeWithKey(fn: (str: string, x: any, z: any) => any, a: U, b: V): U & V; + mergeWithKey(fn: (str: string, x: any, z: any) => any, a: U): (b: V) => U & V; + mergeWithKey(fn: (str: string, x: any, z: any) => any): (a: U, b: V) => U & V; + + /** + * Returns the smaller of its two arguments. + */ + min(a: Ord, b: Ord): Ord; + min(a: Ord): (b: Ord) => Ord; + + /** + * Takes a function and two values, and returns whichever value produces + * the smaller result when passed to the provided function. + */ + minBy(keyFn: (a: T) => Ord, a: T, b: T): T; + minBy(keyFn: (a: T) => Ord, a: T): (b: T) => T; + minBy(keyFn: (a: T) => Ord): CurriedFunction2 + + /** + * Divides the second parameter by the first and returns the remainder. + * The flipped version (`moduloBy`) may be more useful curried. + * Note that this functions preserves the JavaScript-style behavior for + * modulo. For mathematical modulo see `mathMod` + */ + modulo(a: number, b: number): number; + modulo(a: number): (b: number) => number; + + /** + * Multiplies two numbers. Equivalent to a * b but curried. + */ + multiply(a: number, b: number): number; + multiply(a: number): (b: number) => number; + + + /** + * Wraps a function of any arity (including nullary) in a function that accepts exactly n parameters. + * Any extraneous parameters will not be passed to the supplied function. + */ + nAry(n: number, fn: (...arg: any[]) => any): Function; + + /** + * Negates its argument. + */ + negate(n: number): number; + + + /** + * Returns true if no elements of the list match the predicate, false otherwise. + */ + none(fn: (a: T) => boolean, list: T[]): boolean; + none(fn: (a: T) => boolean): (list: T[]) => boolean; + + + /** + * A function wrapping a call to the given function in a `!` operation. It will return `true` when the + * underlying function would return a false-y value, and `false` when it would return a truth-y one. + */ + not(value: any): boolean; + + /** + * Returns the nth element in a list. + */ + nth(n: number, list: T[]): T; + nth(n: number): (list: T[]) => T; + + /** + * Returns a function which returns its nth argument. + */ + nthArg(n: number): (...a: any[]) => any; + + /** + * Creates an object containing a single key:value pair. + */ + objOf(key: string, value: T): {string: T}; + objOf(key: string): (value: T) => {string: T}; + + /** + * Returns a singleton array containing the value provided. + */ + of(x: T): T[]; + //of(x: T[]): T[][]; unnecessary typing and introduced error in unless example + + /** + * Returns a partial copy of an object omitting the keys specified. + */ + omit(names: string[], obj: T): T; + omit(names: string[]): (obj: T) => T; + + /** + * Accepts a function fn and returns a function that guards invocation of fn such that fn can only ever be + * called once, no matter how many times the returned function is invoked. The first value calculated is + * returned in subsequent invocations. + */ + once(fn: Function): Function; + + /** + * A function that returns the first truthy of two arguments otherwise the last argument. Note that this is + * NOT short-circuited, meaning that if expressions are passed they are both evaluated. + * Dispatches to the or method of the first argument if applicable. + */ + or(a: T, b: U): T|U; + or(a: T): (b: U) => T|U; + or(fn1: T, val2: U): T|U; + or(fn1: T): (val2: U) => T|U; + + + /** + * Returns the result of "setting" the portion of the given data structure + * focused by the given lens to the given value. + */ + over(lens: Lens, fn: Arity1Fn, value: T): T; + over(lens: Lens, fn: Arity1Fn, value: T[]): T[]; + over(lens: Lens, fn: Arity1Fn): (value: T) => T; + over(lens: Lens, fn: Arity1Fn): (value: T[]) => T[]; + over(lens: Lens): (fn: Arity1Fn, value: T) => T; + over(lens: Lens): (fn: Arity1Fn, value: T[]) => T[]; + + + /** + * Takes two arguments, fst and snd, and returns [fst, snd]. + */ + pair(fst: F, snd: S): [F, S]; + + /** + * Accepts as its arguments a function and any number of values and returns a function that, + * when invoked, calls the original function with all of the values prepended to the + * original function's arguments list. In some libraries this function is named `applyLeft`. + */ + partial(fn: Function, ...args: any[]): Function; + + /** + * Accepts as its arguments a function and any number of values and returns a function that, + * when invoked, calls the original function with all of the values appended to the original + * function's arguments list. + */ + partialRight(fn: Function, ...args: any[]): Function; + + /** + * Takes a predicate and a list and returns the pair of lists of elements + * which do and do not satisfy the predicate, respectively. + */ + partition(fn: (a: string) => boolean, list: string[]): string[][]; + partition(fn: (a: T) => boolean, list: T[]): T[][]; + partition(fn: (a: T) => boolean): (list: T[]) => T[][]; + partition(fn: (a: string) => boolean): (list: string[]) => string[][]; + + /** + * Retrieve the value at a given path. + */ + path(path: string[], obj: any): T; + path(path: string[]): (obj: any) => T; + + /** + * Determines whether a nested path on an object has a specific value, + * in `R.equals` terms. Most likely used to filter a list. + */ + pathEq(path: string[], val: any, obj: any): boolean; + pathEq(path: string[], val: any): (obj: any) => boolean; + pathEq(path: string[]): (val: any, obj: any) => boolean; + pathEq(path: string[]): (val: any) => (obj: any) => boolean; + + /** + * If the given, non-null object has a value at the given path, returns the value at that path. + * Otherwise returns the provided default value. + */ + pathOr(d: T, p: string[], obj: any): T|any; + pathOr(d: T, p: string[]): (obj: any) => T|any; + pathOr(d: T): (p: string[], obj: any) => T|any; + + + /** + * Returns a partial copy of an object containing only the keys specified. If the key does not exist, the + * property is ignored. + */ + pick(names: string[], obj: T): U; + pick(names: string[]): (obj: T) => U; + + + /** + * Similar to `pick` except that this one includes a `key: undefined` pair for properties that don't exist. + */ + pickAll(names: string[], obj: T): U; + pickAll(names: string[]): (obj: T) => U; + + + /** + * Returns a partial copy of an object containing only the keys that satisfy the supplied predicate. + */ + pickBy(pred: ObjPred, obj: T): U; + pickBy(pred: ObjPred): (obj: T) => U; + + + /** + * Creates a new function that runs each of the functions supplied as parameters in turn, + * passing the return value of each function invocation to the next function invocation, + * beginning with whatever arguments were passed to the initial invocation. + */ + pipe(fn0: (x0: V0) => T1): (x0: V0) => T1; + pipe(fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T1; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T1; + + pipe(fn0: (x0: V0) => T1, fn1: (x: T1) => T2): (x0: V0) => T2; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2): (x0: V0, x1: V1) => T2; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2): (x0: V0, x1: V1, x2: V2) => T2; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x: V0) => T3; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x0: V0, x1: V1) => T3; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x0: V0, x1: V1, x2: V2) => T3; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x: V0) => T4; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x0: V0, x1: V1) => T4; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x0: V0, x1: V1, x2: V2) => T4; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x: V0) => T5; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x0: V0, x1: V1) => T5; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x0: V0, x1: V1, x2: V2) => T5; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x: V0) => T6; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x0: V0, x1: V1) => T6; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x0: V0, x1: V1, x2: V2) => T6; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn: (x: T6) => T7): (x: V0) => T7; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7): (x0: V0, x1: V1) => T7; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7): (x0: V0, x1: V1, x2: V2) => T7; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7, fn: (x: T7) => T8): (x: V0) => T8; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T5) => T6, fn7: (x: T7) => T8): (x0: V0, x1: V1) => T8; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T5) => T6, fn7: (x: T7) => T8): (x0: V0, x1: V1, x2: V2) => T8; + + + /** + * Returns a new list by plucking the same named property off all objects in the list supplied. + */ + pluck(p: string|number, list: any[]): T[]; + pluck(p: string|number): (list: any[]) => T[]; + + /** + * Returns a new list with the given element at the front, followed by the contents of the + * list. + */ + prepend(el: T, list: T[]): T[]; + prepend(el: T): (list: T[]) => T[]; + + /** + * Multiplies together all the elements of a list. + */ + product(list: number[]): number; + + + /** + * Reasonable analog to SQL `select` statement. + */ + project(props: string[], objs: T[]): U[]; + + /** + * Returns a function that when supplied an object returns the indicated property of that object, if it exists. + * Note: TS1.9 # replace any by dictionary + */ + prop(p: string, obj: any): T; + prop(p: string): (obj: any) => T; + + /** + * Determines whether the given property of an object has a specific + * value according to strict equality (`===`). Most likely used to + * filter a list. + */ + // propEq(name: string, val: T, obj: {[index:string]: T}): boolean; + // propEq(name: string, val: T, obj: {[index:number]: T}): boolean; + propEq(name: string, val: T, obj: any): boolean; + // propEq(name: number, val: T, obj: any): boolean; + propEq(name: string, val: T): (obj: any) => boolean; + // propEq(name: number, val: T): (obj: any) => boolean; + propEq(name: string): (val: T, obj: any) => boolean; + // propEq(name: number): (val: T, obj: any) => boolean; + + /** + * Returns true if the specified object property is of the given type; false otherwise. + */ + propIs(type: any, name: string, obj: any): boolean; + propIs(type: any, name: string): (obj: any) => boolean; + propIs(type: any): { + (name: string, obj: any): boolean; + (name: string): (obj: any) => boolean; + } + + /** + * If the given, non-null object has an own property with the specified name, returns the value of that property. + * Otherwise returns the provided default value. + */ + propOr(val: T, p: string, obj: U): V; + propOr(val: T, p: string): (obj: U) => V; + propOr(val: T): (p: string, obj: U) => V; + + /** + * Returns the value at the specified property. + * The only difference from `prop` is the parameter order. + * Note: TS1.9 # replace any by dictionary + */ + props(ps: string[], obj: any): T[]; + props(ps: string[]): (obj: any) => T[]; + + /** + * Returns true if the specified object property satisfies the given predicate; false otherwise. + */ + propSatisfies(pred: (val: T) => boolean, name: string, obj: U): boolean; + propSatisfies(pred: (val: T) => boolean, name: string): (obj: U) => boolean; + propSatisfies(pred: (val: T) => boolean): CurriedFunction2; + + /** + * Returns a list of numbers from `from` (inclusive) to `to` + * (exclusive). In mathematical terms, `range(a, b)` is equivalent to + * the half-open interval `[a, b)`. + */ + range(from: number, to: number): number[]; + range(from: number): (to: number) => number[]; + + /** + * Returns a single item by iterating through the list, successively calling the iterator + * function and passing it an accumulator value and the current value from the array, and + * then passing the result to the next call. + */ + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult, list: T[]): TResult; + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced): (acc: TResult, list: T[]) => TResult; + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult): (list: T[]) => TResult; + + /** + * Groups the elements of the list according to the result of calling the String-returning function keyFn on each + * element and reduces the elements of each group to a single value via the reducer function valueFn. + */ + reduceBy(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult, keyFn: (elem: T) => string, list: T[]): {[index: string]: TResult}; + reduceBy(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult, keyFn: (elem: T) => string): (list: T[]) => {[index: string]: TResult}; + reduceBy(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult): CurriedFunction2<(elem: T) => string, T[], {[index: string]: TResult}>; + reduceBy(valueFn: (acc: TResult, elem: T) => TResult): CurriedFunction3 string, T[], {[index: string]: TResult}>; + + /** + * Returns a value wrapped to indicate that it is the final value of the reduce and + * transduce functions. The returned value should be considered a black box: the internal + * structure is not guaranteed to be stable. + */ + reduced(elem: T): Reduced; + + /** + * Returns a single item by iterating through the list, successively calling the iterator + * function and passing it an accumulator value and the current value from the array, and + * then passing the result to the next call. + */ + reduceRight(fn: (acc: TResult, elem: T) => TResult, acc: TResult, list: T[]): TResult; + reduceRight(fn: (acc: TResult, elem: T) => TResult): (acc: TResult, list: T[]) => TResult; + reduceRight(fn: (acc: TResult, elem: T) => TResult, acc: TResult): (list: T[]) => TResult; + + /** + * Similar to `filter`, except that it keeps only values for which the given predicate + * function returns falsy. + */ + reject(fn: (value: T) => boolean, list: T[]): T[]; + reject(fn: (value: T) => boolean): (list: T[]) => T[]; + + /** + * Removes the sub-list of `list` starting at index `start` and containing `count` elements. + */ + remove(start: number, count: number, list: T[]): T[]; + remove(start: number): (count: number, list: T[]) => T[]; + remove(start: number, count: number): (list: T[]) => T[]; + + /** + * Returns a fixed list of size n containing a specified identical value. + */ + repeat(a: T, n: number): T[]; + repeat(a: T): (n: number) => T[]; + + + /** + * Replace a substring or regex match in a string with a replacement. + */ + replace(pattern: RegExp, replacement: string, str: string): string; + replace(pattern: RegExp, replacement: string): (str: string) => string; + replace(pattern: RegExp): (replacement: string) => (str: string) => string; + replace(pattern: String, replacement: string, str: string): string; + replace(pattern: String, replacement: string): (str: string) => string; + replace(pattern: String): (replacement: string) => (str: string) => string; + + + /** + * Returns a new list with the same elements as the original list, just in the reverse order. + */ + reverse(list: T[]): T[]; + + /** + * Scan is similar to reduce, but returns a list of successively reduced values from the left. + */ + scan(fn: (acc: TResult, elem: T) => any, acc: TResult, list: T[]): TResult[]; + scan(fn: (acc: TResult, elem: T) => any, acc: TResult): (list: T[]) => TResult[]; + scan(fn: (acc: TResult, elem: T) => any): (acc: TResult, list: T[]) => TResult[]; + + /** + * Returns the result of "setting" the portion of the given data structure focused by the given lens to the + * given value. + */ + set(lens: Lens, a: U, obj: T): T; + set(lens: Lens, a: U): (obj: T) => T; + set(lens: Lens): (a: U, obj: T) => T; + + /** + * Returns the elements from `xs` starting at `a` and ending at `b - 1`. + */ + slice(a: number, b: number, list: string): string; + slice(a: number, b: number, list: T[]): T[]; + slice(a: number, b: number): (list: string|T[]) => string|T[]; + slice(a: number): (b: number, list: string|T[]) => string|T[]; + + /** + * Returns a copy of the list, sorted according to the comparator function, which should accept two values at a + * time and return a negative number if the first value is smaller, a positive number if it's larger, and zero + * if they are equal. + */ + sort(fn: (a: T, b: T) => number, list: T[]): T[]; + sort(fn: (a: T, b: T) => number): (list: T[]) => T[]; + + + /** + * Sorts the list according to a key generated by the supplied function. + */ + sortBy(fn: (a: any) => string, list: T[]): T[]; + sortBy(fn: (a: any) => string): (list: T[]) => T[]; + + /** + * Splits a string into an array of strings based on the given + * separator. + */ + split(sep: string): (str: string) => string[]; + split(sep: RegExp): (str: string) => string[]; + split(sep: string, str: string): string[]; + split(sep: RegExp, str: string): string[]; + + /** + * Splits a given list or string at a given index. + */ + splitAt(index: number, list: T): T[]; + splitAt(index: number): (list: T) => T[]; + splitAt(index: number, list: T[]): T[][]; + splitAt(index: number): (list: T[]) => T[][]; + + /** + * Splits a collection into slices of the specified length. + */ + splitEvery(a: number, list: T[]): T[][]; + splitEvery(a: number): (list: T[]) => T[][]; + + + /** + * Takes a list and a predicate and returns a pair of lists with the following properties: + * - the result of concatenating the two output lists is equivalent to the input list; + * - none of the elements of the first output list satisfies the predicate; and + * - if the second output list is non-empty, its first element satisfies the predicate. + */ + splitWhen(pred: (val: T) => boolean, list: U[]): U[][]; + splitWhen(pred: (val: T) => boolean): (list: U[]) => U[][]; + + /** + * Subtracts two numbers. Equivalent to `a - b` but curried. + */ + subtract(a: number, b: number): number; + subtract(a: number): (b: number) => number; + + /** + * Adds together all the elements of a list. + */ + sum(list: number[]): number; + + /** + * Finds the set (i.e. no duplicates) of all elements contained in the first or second list, but not both. + */ + symmetricDifference(list1: T[], list2: T[]): T[]; + symmetricDifference(list: T[]): (list: T[]) => T[]; + + /** + * Finds the set (i.e. no duplicates) of all elements contained in the first or second list, but not both. + * Duplication is determined according to the value returned by applying the supplied predicate to two list elements. + */ + symmetricDifferenceWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + symmetricDifferenceWith(pred: (a: T, b: T) => boolean): CurriedFunction2; + + /** + * A function that always returns true. Any passed in parameters are ignored. + */ + T(): boolean; + + /** + * Returns all but the first element of a list. + */ + tail(list: T[]): T[]; + + /** + * Returns a new list containing the first `n` elements of the given list. If + * `n > * list.length`, returns a list of `list.length` elements. + */ + take(n: number, xs: T[]): T[]; + take(n: number, xs: string): string; + take(n: number): { + (xs: string): string; + (xs: T[]): T[]; + } + + + /** + * Returns a new list containing the last n elements of the given list. If n > list.length, + * returns a list of list.length elements. + */ + takeLast(n: number, xs: T[]): T[]; + takeLast(n: number, xs: string): string; + takeLast(n: number): { + (xs: T[]): T[]; + (xs: string): string; + } + + /** + * Returns a new list containing the last n elements of a given list, passing each value + * to the supplied predicate function, and terminating when the predicate function returns + * false. Excludes the element that caused the predicate function to fail. The predicate + * function is passed one argument: (value). + */ + takeLastWhile(pred: (a: T) => Boolean, list: T[]): T[]; + takeLastWhile(pred: (a: T) => Boolean): (list: T[]) => T[]; + + /** + * Returns a new list containing the first `n` elements of a given list, passing each value + * to the supplied predicate function, and terminating when the predicate function returns + * `false`. + */ + takeWhile(fn: (x: T) => boolean, list: T[]): T[]; + takeWhile(fn: (x: T) => boolean): (list: T[]) => T[]; + + /** + * The function to call with x. The return value of fn will be thrown away. + */ + tap(fn: (a: T) => any, value: T): T; + tap(fn: (a: T) => any): (value: T) => T; + + /** + * Determines whether a given string matches a given regular expression. + */ + test(regexp: RegExp, str: string): boolean; + test(regexp: RegExp): (str: string) => boolean; + + /** + * Calls an input function `n` times, returning an array containing the results of those + * function calls. + */ + times(fn: (i: number) => T, n: number): T[]; + times(fn: (i: number) => T): (n: number) => T[]; + + + /** + * The lower case version of a string. + */ + toLower(str: string): string; + + /** + * Converts an object into an array of key, value arrays. + * Only the object's own properties are used. + * Note that the order of the output array is not guaranteed to be + * consistent across different JS platforms. + */ + toPairs(obj: {[k: string]: S} | {[k: number]: S} | any): [F,S][]; + + /** + * Converts an object into an array of key, value arrays. + * The object's own properties and prototype properties are used. + * Note that the order of the output array is not guaranteed to be + * consistent across different JS platforms. + */ + toPairsIn(obj: {[k: string]: S} | {[k: number]: S} | any): [F,S][]; + + /** + * Returns the string representation of the given value. eval'ing the output should + * result in a value equivalent to the input value. Many of the built-in toString + * methods do not satisfy this requirement. + * + * If the given value is an [object Object] with a toString method other than + * Object.prototype.toString, this method is invoked with no arguments to produce the + * return value. This means user-defined constructor functions can provide a suitable + * toString method. + */ + toString(val: T): string; + + /** + * The upper case version of a string. + */ + toUpper(str: string): string; + + /** + * Initializes a transducer using supplied iterator function. Returns a single item by iterating through the + * list, successively calling the transformed iterator function and passing it an accumulator value and the + * current value from the array, and then passing the result to the next call. + */ + transduce(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[], acc: T[], list: T[]): U; + transduce(xf: (arg: T[]) => T[]): (fn: (acc: U[], val: U) => U[], acc: T[], list: T[]) => U; + transduce(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[]): (acc: T[], list: T[]) => U; + transduce(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[], acc: T[]): (list: T[]) => U; + + /** + * Transposes the rows and columns of a 2D list. When passed a list of n lists of length x, returns a list of x lists of length n. + */ + transpose(list: any[][]): any[][]; + + /** + * Removes (strips) whitespace from both ends of the string. + */ + trim(str: string): string; + + /** + * tryCatch takes two functions, a tryer and a catcher. The returned function evaluates the tryer; if it does + * not throw, it simply returns the result. If the tryer does throw, the returned function evaluates the catcher + * function and returns its result. Note that for effective composition with this function, both the tryer and + * catcher functions must return the same type of results. + */ + tryCatch(tryer: (...args: any[]) => T, catcher: (...args: any[]) => T, x: any): T; + + /** + * Gives a single-word string description of the (native) type of a value, returning such answers as 'Object', + * 'Number', 'Array', or 'Null'. Does not attempt to distinguish user Object types any further, reporting them + * all as 'Object'. + */ + type(val: any): string; + + /** + * Takes a function fn, which takes a single array argument, and returns a function which: + * - takes any number of positional arguments; + * - passes these arguments to fn as an array; and + * - returns the result. + * In other words, R.unapply derives a variadic function from a function which takes an array. + * R.unapply is the inverse of R.apply. + */ + unapply(fn: (args: any[]) => T): (...args: any[]) => T; + + /** + * Wraps a function of any arity (including nullary) in a function that accepts exactly 1 parameter. + * Any extraneous parameters will not be passed to the supplied function. + */ + unary(fn: (a: T, ...args: any[]) => any): (a: T) => any + + /** + * Returns a function of arity n from a (manually) curried function. + */ + uncurryN(len: number, fn: (a: any) => any): (...a: any[]) => T; + + /** + * Builds a list from a seed value. Accepts an iterator function, which returns either false + * to stop iteration or an array of length 2 containing the value to add to the resulting + * list and the seed to be used in the next call to the iterator function. + */ + unfold(fn: (seed: T) => TResult[]|boolean, seed: T): TResult[]; + unfold(fn: (seed: T) => TResult[]|boolean): (seed: T) => TResult[]; + + /** + * Combines two lists into a set (i.e. no duplicates) composed of the + * elements of each list. + */ + union(as: T[], bs: T[]): T[]; + union(as: T[]): (bs: T[]) => T[]; + + /** + * Combines two lists into a set (i.e. no duplicates) composed of the elements of each list. Duplication is + * determined according to the value returned by applying the supplied predicate to two list elements. + */ + unionWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + unionWith(pred: (a: T, b: T) => boolean): CurriedFunction2 + + /** + * Returns a new list containing only one copy of each element in the original list. + */ + uniq(list: T[]): T[]; + + /** + * Returns a new list containing only one copy of each element in the original list, based upon the value returned by applying the supplied function to each list element. Prefers the first item if the supplied function produces the same value on two items. R.equals is used for comparison. + */ + uniqBy(fn: (a: T) => U, list: T[]): T[]; + uniqBy(fn: (a: T) => U): (list: T[]) => T[]; + + /** + * Returns a new list containing only one copy of each element in the original list, based upon the value + * returned by applying the supplied predicate to two list elements. + */ + uniqWith(pred: (x: T, y: T) => boolean, list: T[]): T[]; + uniqWith(pred: (x: T, y: T) => boolean): (list: T[]) => T[]; + + /** + * Tests the final argument by passing it to the given predicate function. If the predicate is not satisfied, + * the function will return the result of calling the whenFalseFn function with the same argument. If the + * predicate is satisfied, the argument is returned as is. + */ + unless(pred: (a: T) => boolean, whenFalseFn: (a: T) => U, obj: T): U; + unless(pred: (a: T) => boolean, whenFalseFn: (a: T) => U): (obj: T) => U; + + /** + * Returns a new list by pulling every item at the first level of nesting out, and putting + * them in a new array. + */ + unnest(x: T[][]): T[]; + unnest(x: T[]): T[]; + + /** + * Takes a predicate, a transformation function, and an initial value, and returns a value of the same type as + * the initial value. It does so by applying the transformation until the predicate is satisfied, at which point + * it returns the satisfactory value. + */ + until(pred: (val: T) => boolean, fn: (val: T) => U, init: U): U; + until(pred: (val: T) => boolean, fn: (val: T) => U): (init: U) => U; + + /** + * Returns a new copy of the array with the element at the provided index replaced with the given value. + */ + update(index: number, value: T, list: T[]): T[]; + update(index: number, value: T): (list: T[]) => T[]; + + /** + * Accepts a function fn and a list of transformer functions and returns a new curried function. + * When the new function is invoked, it calls the function fn with parameters consisting of the + * result of calling each supplied handler on successive arguments to the new function. + * + * If more arguments are passed to the returned function than transformer functions, those arguments + * are passed directly to fn as additional parameters. If you expect additional arguments that don't + * need to be transformed, although you can ignore them, it's best to pass an identity function so + * that the new function reports the correct arity. + */ + useWith(fn: Function, transformers: Function[]): Function; + + /** + * Returns a list of all the enumerable own properties of the supplied object. + * Note that the order of the output array is not guaranteed across + * different JS platforms. + */ + values(obj: {[index: string]: T}): T[]; + values(obj: any): T[]; + + /** + * Returns a list of all the properties, including prototype properties, of the supplied + * object. Note that the order of the output array is not guaranteed to be consistent across different JS platforms. + */ + valuesIn(obj: any): T[]; + + /** + * Returns a "view" of the given data structure, determined by the given lens. The lens's focus determines which + * portion of the data structure is visible. + */ + view(lens: Lens, obj: T): U; + + /** + * Tests the final argument by passing it to the given predicate function. If the predicate is satisfied, the function + * will return the result of calling the whenTrueFn function with the same argument. If the predicate is not satisfied, + * the argument is returned as is. + */ + when(pred: (a: T) => boolean, whenTrueFn: (a: T) => U, obj: T): U; + when(pred: (a: T) => boolean, whenTrueFn: (a: T) => U): (obj: T) => U; + + /** + * Takes a spec object and a test object and returns true if the test satisfies the spec. + * Any property on the spec that is not a function is interpreted as an equality + * relation. + * + * If the spec has a property mapped to a function, then `where` evaluates the function, passing in + * the test object's value for the property in question, as well as the whole test object. + * + * `where` is well suited to declarativley expressing constraints for other functions, e.g., + * `filter`, `find`, `pickWith`, etc. + */ + where(spec: T, testObj: U): boolean; + where(spec: T): (testObj: U) => boolean; + where(spec: ObjFunc2, testObj: U): boolean; + where(spec: ObjFunc2): (testObj: U) => boolean; + + /** + * Takes a spec object and a test object; returns true if the test satisfies the spec, + * false otherwise. An object satisfies the spec if, for each of the spec's own properties, + * accessing that property of the object gives the same value (in R.eq terms) as accessing + * that property of the spec. + */ + whereEq(spec: T, obj: U): boolean; + whereEq(spec: T): (obj: U) => boolean; + + /** + * Returns a new list without values in the first argument. R.equals is used to determine equality. + * Acts as a transducer if a transformer is given in list position. + */ + without(list1: T[], list2: T[]): T[]; + without(list1: T[]): (list2: T[]) => T[]; + + /** + * Wrap a function inside another to allow you to make adjustments to the parameters, or do other processing + * either before the internal function is called or with its results. + */ + wrap(fn: Function, wrapper: Function): Function; + + /** + * Creates a new list out of the two supplied by creating each possible pair from the lists. + */ + xprod(as: K[], bs: V[]): KeyValuePair[]; + xprod(as: K[]): (bs: V[]) => KeyValuePair[]; + + /** + * Creates a new list out of the two supplied by pairing up equally-positioned items from + * both lists. Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`. + */ + zip(list1: K[], list2: V[]): KeyValuePair[]; + zip(list1: K[]): (list2: V[]) => KeyValuePair[]; + + /** + * Creates a new object out of a list of keys and a list of values. + */ + // TODO: Dictionary as a return value is to specific, any seems to loose + zipObj(keys: string[], values: T[]): {[index:string]: T}; + zipObj(keys: string[]): (values: T[]) => {[index:string]: T}; + + + /** + * Creates a new list out of the two supplied by applying the function to each + * equally-positioned pair in the lists. + */ + zipWith(fn: (x: T, y: U) => TResult, list1: T[], list2: U[]): TResult[]; + zipWith(fn: (x: T, y: U) => TResult, list1: T[]): (list2: U[]) => TResult[]; + zipWith(fn: (x: T, y: U) => TResult): (list1: T[], list2: U[]) => TResult[]; + + } +} + +export = R; From 5433909c8b63d013257193c4dec60ac93ce05d77 Mon Sep 17 00:00:00 2001 From: Erwin Poeze Date: Tue, 16 Aug 2016 08:38:54 +0200 Subject: [PATCH 038/844] ramda typings --- ramda/ramda-tests.ts | 1952 ++++++++++++++++++++++++++++++++++++++++++ ramda/ramda.d.ts | 1807 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 3759 insertions(+) create mode 100644 ramda/ramda-tests.ts create mode 100644 ramda/ramda.d.ts diff --git a/ramda/ramda-tests.ts b/ramda/ramda-tests.ts new file mode 100644 index 0000000000..15ec5eb274 --- /dev/null +++ b/ramda/ramda-tests.ts @@ -0,0 +1,1952 @@ +import * as R from './ramda'; + +var double = function(x: number): number { + return x + x +}; + +var shout = function(x: number): string { + return x >= 10 + ? 'big' + : 'small' +}; + +class F { + x = 'X'; + y = 'Y'; +} +class F2 { + a = 100; + y = 1; + x(){}; + z() {}; +} + +(() => { + var x: boolean; + x = R.isArrayLike('a'); + x = R.isArrayLike([1,2,3]); + x = R.isArrayLike([]); +}); + +(() => { + R.propIs(Number, 'x', {x: 1, y: 2}); //=> true + R.propIs(Number, 'x')({x: 1, y: 2}); //=> true + R.propIs(Number)('x', {x: 1, y: 2}); //=> true + R.propIs(Number)('x')({x: 1, y: 2}); //=> true + R.propIs(Number, 'x', {x: 'foo'}); //=> false + R.propIs(Number, 'x', {}); //=> false +}); + +(() => { + R.type({}); //=> "Object" + R.type(1); //=> "Number" + R.type(false); //=> "Boolean" + R.type('s'); //=> "String" + R.type(null); //=> "Null" + R.type([]); //=> "Array" + R.type(/[A-z]/); //=> "RegExp" +}); + +() => { + var takesNoArg = function() { return true; }; + var takesOneArg = function(a: number) { return [a]; }; + var takesTwoArgs = function(a: number, b: number) { return [a, b]; }; + var takesThreeArgs = function(a: number, b: number, c: number) { return [a, b, c]; }; + + var addFourNumbers = function(a: number, b: number, c: number, d: number): number { + return a + b + c + d; + }; + + var x1: Function = R.curry(addFourNumbers) + // because of the current way of currying, the following call results in a type error + // var x2: Function = R.curry(addFourNumbers)(1,2,4) + var x3: Function = R.curry(addFourNumbers)(1)(2) + var x4: Function = R.curry(addFourNumbers)(1)(2)(3) + var y1: number = R.curry(addFourNumbers)(1)(2)(3)(4) + var y2: number = R.curry(addFourNumbers)(1,2)(3,4) + var y3: number = R.curry(addFourNumbers)(1,2,3)(4) + + R.nAry(0, takesNoArg); + R.nAry(0, takesOneArg); + R.nAry(1, takesTwoArgs); + R.nAry(1, takesThreeArgs); + + var u1: {(a: any): any} = R.unary(takesOneArg); + var u2: {(a: any): any} = R.unary(takesTwoArgs); + var u3: {(a: any): any} = R.unary(takesThreeArgs); + + R.binary(takesTwoArgs); + R.binary(takesThreeArgs); + + var addTwoNumbers = function(a:number, b:number) { return a + b; } + var addTwoNumbersCurried = R.curry(addTwoNumbers); + + var inc = addTwoNumbersCurried(1); + var z1:number = inc(2); + var z2:number = addTwoNumbersCurried(2,3); +} + +() => { + const addFour = (a:number) => (b:number) => (c:number) => (d:number) => a + b + c + d; + const uncurriedAddFour = R.uncurryN(4, addFour); + const res: number = uncurriedAddFour(1, 2, 3, 4); //=> 10 +} + +() => { + // coerceArray :: (a|[a]) -> [a] + const coerceArray = R.unless(R.isArrayLike, R.of); + const a: number[] = coerceArray([1, 2, 3]); //=> [1, 2, 3] + const b: number[] = coerceArray(1); //=> [1] +} + +(() => { + R.nthArg(1)('a', 'b', 'c'); //=> 'b' + R.nthArg(-1)('a', 'b', 'c'); //=> 'c' +}); + +() => { + const fn: (...args: string[])=>string = R.unapply(JSON.stringify); + const res: string = R.unapply(JSON.stringify)(1, 2, 3); //=> '[1,2,3]' +} + +() => { + const a: number = R.until(R.flip(R.gt)(100), R.multiply(2))(1) // => 128 +} + +() => { + const truncate = R.when( + R.propSatisfies(R.flip(R.gt)(10), 'length'), + R.pipe(R.take(10), R.append('…'), R.join('')) + ); + const a: string = truncate('12345'); //=> '12345' + const b: string = truncate('0123456789ABC'); //=> '0123456789…' +} + +/* compose */ +() => { + var double = function(x: number): number { + return x + x + } + var limit10 = function(x: number): boolean { + return x >= 10 + } + var func: (x: number) => boolean = R.compose(limit10, double) + var res: boolean = R.compose(limit10, double)(10) + + const f0 = (s: string) => +s; // string -> number + const f1 = (n: number) => n === 1; // number -> boolean + const f2 = R.compose(f1, f0); // string -> boolean + + // akward example that bounces types between number and string + const g0 = (list: number[]) => R.map(R.inc, list); + const g1 = R.dropWhile(R.gt(10)); + const g2 = R.map((i: number) => i > 5 ? 'bigger' : 'smaller'); + const g3 = R.all((i: string) => i === 'smaller'); + const g = R.compose(g3, g2, g1, g0); + const g_res: boolean = g([1, 2, 10, 13]); +} + +/* pipe */ +() => { + var func: (x: number) => string = R.pipe(double, double, shout) + var res: string = R.pipe(double, double, shout)(10); + + const capitalize = (str: string) => R.pipe( + R.split(''), + R.adjust(R.toUpper, 0), + R.join('') + )(str); + + var f = R.pipe(Math.pow, R.negate, R.inc); + var fr: number = f(3, 4); // -(3^4) + 1 +} + +() => { + R.invoker('charAt', String.prototype); + R.invoker('charAt', String.prototype, 1); +} + +(() => { + const range = R.juxt([Math.min, Math.max]); + range(3, 4, 9, -3); //=> [-3, 9] + + const chopped = R.juxt([R.head, R.last]); + chopped('longstring'); // => ["l", "g"] +}); + +var square = function(x: number) { return x * x; }; +var add = function(a: number, b: number) { return a + b; }; +// Adds any number of arguments together +var addAll = function() { + return 0; +}; + +// Basic example +R.useWith(addAll, [ double, square ]); + +(() => { + var printXPlusFive = function(x: number) { console.log(x + 5); }; + R.forEach(printXPlusFive, [1, 2, 3]); + R.clone([{},{},{}]) + R.clone([1,2,3]); +})(); + +// (() => { +// var printXPlusFive = function(x, i) { console.log(i + 5); }; +// R.forEach.idx(printXPlusFive, [{name: 1}, {name: 2}, {name: 3}]); +// })(); + +var i = function(x: number) {return x;}; +R.times(i, 5); + +(() => { + var triple = function(x: number): number { return x * 3; }; + var square = function(x: number): number { return x * x; }; + var squareThenDoubleThenTriple = R.pipe(square, double, triple); + squareThenDoubleThenTriple(5); //=> 150 + + +})(); + +(() => { + var multiply = function(a: number, b: number) { return a * b; }; + var double = R.partial(multiply, 2); + double(2); //=> 4 + + var greet = function(salutation: string, title: string, firstName: string, lastName: string) { + return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; + }; + var sayHello = R.partial(greet, 'Hello'); + var sayHelloToMs = R.partial(sayHello, 'Ms.'); + sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!' + + var greetMsJaneJones = R.partialRight(greet, 'Ms.', 'Jane', 'Jones'); + greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!' +})(); + +(() => { + var numberOfCalls = 0; + var trackedAdd = function(a: number, b: number) { + numberOfCalls += 1; + return a + b; + }; + var memoTrackedAdd = R.memoize(trackedAdd); + + memoTrackedAdd(1, 2); //=> 3 + numberOfCalls; //=> 1 + memoTrackedAdd(1, 2); //=> 3 + numberOfCalls; //=> 1 + memoTrackedAdd(2, 3); //=> 5 + numberOfCalls; //=> 2 + + // Note that argument order matters + memoTrackedAdd(2, 1); //=> 3 + numberOfCalls; //=> 3 +})(); + +(() => { + var addOneOnce = R.once(function(x: number){ return x + 1; }); + addOneOnce(10); //=> 11 + addOneOnce(addOneOnce(50)); //=> 11 +})(); + +(() => { + var slashify = R.wrap(R.flip(R.add)('/'), function(f: Function, x: string) { + return R.match(/\/$/, x) ? x : f(x); + }); + + slashify('a'); //=> 'a/' + slashify('a/'); //=> 'a/' +})(); + + + +(() => { + var numbers = [1, 2, 3]; + var add = function(a: number, b: number) { + return a + b + }; + R.reduce(add, 10, numbers); //=> 16; +})(); + +(() => { + var plus3 = R.add(3); +})(); + +(() => { + var pairs = [ ['a', 1], ['b', 2], ['c', 3] ]; + var flattenPairs = function(acc: [string, number], pair: [string, number]) { + return acc.concat(pair); + }; + R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] +})(); + +(() => { + var values = { x: 1, y: 2, z: 3 }; + var prependKeyAndDouble = function(num: number, key: string, obj: any) { + return key + (num * 2); + }; + R.mapObjIndexed(prependKeyAndDouble, values); //=> { x: 'x2', y: 'y4', z: 'z6' } +}); + +(() => { + const a: number[] = R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6] + const b: number[][] = R.of([1]); //=> [[1]] + const c: number[] = R.of(1); + +}); + +() => { + const a1 = R.empty([1,2,3,4,5]); //=> [] + const a2 = R.empty([1, 2, 3]); //=> [] + const a3 = R.empty('unicorns'); //=> '' + const a4 = R.empty({x: 1, y: 2}); //=> {} +} + +(() => { + R.length([1, 2, 3]); //=> 3 +}); + +(() => { + const isEven = function(n: number) { + return n % 2 === 0; + }; + const filterIndexed = R.addIndex(R.filter); + + R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4] + + var lastTwo = function(val: number, idx: number, list: number[]) { + return list.length - idx <= 2; + }; + filterIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [0, 9] + + var isOdd = function(n: number) { + return n % 2 === 1; + }; + R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] +}); +(() => { + var isNotFour = function(x: number) { + return !(x === 4); + }; + R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3] + R.take(2, [1, 2, 3, 4]); //=> [1, 2] +}); +(() => { + var f = function(n: number) { return n > 50 ? false : [-n, n + 10] }; + let a = R.unfold(f, 10); //=> [-10, -20, -30, -40, -50] + let b = R.unfold(f); //=> [-10, -20, -30, -40, -50] + let c = b(10); +}); +/***************************************************************** + * Function category + */ + + + () => { + var mergeThree = function(a: number, b: number, c: number): number[] { + return ([]).concat(a, b, c); + }; + mergeThree(1, 2, 3); //=> [1, 2, 3] + var flipped = R.flip(mergeThree); + flipped(1, 2, 3); //=> [2, 1, 3] + } + +/********************* + * List category + ********************/ +() => { + var lessThan2 = R.flip(R.lt)(2); + var lessThan3 = R.flip(R.lt)(3); + R.all(lessThan2)([1, 2]); //=> false + R.all(lessThan3)([1, 2]); //=> true +} + +() => { + var lessThan0 = R.flip(R.lt)(0); + var lessThan2 = R.flip(R.lt)(2); + R.any(lessThan0)([1, 2]); //=> false + R.any(lessThan2)([1, 2]); //=> true +} + +() => { + R.aperture(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [2, 3], [3, 4], [4, 5]] + R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]] + R.aperture(7, [1, 2, 3, 4, 5]); //=> [] + R.aperture(7)([1, 2, 3, 4, 5]); //=> [] +} + +() => { + R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests'] + R.append('tests')(['write', 'more']); //=> ['write', 'more', 'tests'] + R.append('tests', []); //=> ['tests'] + R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']] + R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']] + R.append(['tests'])(['write', 'more']); //=> ['write', 'more', ['tests']] + R.append(['tests'])(['write', 'more']); //=> ['write', 'more', ['tests']] +} + +() => { + var duplicate = function(n: number) { + return [n, n]; + }; + R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3] + R.chain(duplicate)([1, 2, 3]); //=> [1, 1, 2, 2, 3, 3] +} + +() => { + R.clamp(1, 10, -1) // => 1 + R.clamp(1, 10)(11) // => 10 + R.clamp(1)(10, 4) // => 4 + R.clamp('a', 'd', 'e') // => 'd' +} + +() => { + R.concat([], []); //=> [] + R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] + R.concat([4, 5, 6])([1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] + R.concat('ABC')('DEF'); // 'ABCDEF' +} + +() => { + R.contains(3)([1, 2, 3]); //=> true + R.contains(3, [1, 2, 3]); //=> true + R.contains(4)([1, 2, 3]); //=> false + R.contains({})([{}, {}]); //=> false + var obj = {}; + R.contains(obj)([{}, obj, {}]); //=> true +} + +() => { + R.drop(3, [1,2,3,4,5,6,7]); //=> [4,5,6,7] + R.drop(3)([1,2,3,4,5,6,7]); //=> [4,5,6,7] + R.drop(3, 'ramda'); //=> 'ram' + R.drop(3)('ramda'); //=> 'ram' +} + +(() => { + R.dropLast(1, ['foo', 'bar', 'baz']); //=> ['foo', 'bar'] + R.dropLast(2)(['foo', 'bar', 'baz']); //=> ['foo'] + R.dropLast(3, 'ramda'); //=> 'ra' + R.dropLast(3)('ramda'); //=> 'ra' +}); + +(() => { + var lteThree = (x: number) => x <= 3; + R.dropLastWhile(lteThree, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3, 4] +}); + +() => { + var lteTwo = function(x: number) { + return x <= 2; + }; + R.dropWhile(lteTwo, [1, 2, 3, 4]); //=> [3, 4] + R.dropWhile(lteTwo)([1, 2, 3, 4]); //=> [3, 4] +} + +() => { + var isEven = function(n: number) { + return n % 2 === 0; + }; + R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4] + var isEvenFn = R.filter(isEven); + isEvenFn([1, 2, 3, 4]); +} + +() => { + var lastTwo = function(val: number, idx: number, list: number[]) { + return list.length - idx <= 2; + }; + var filterIndexed = R.addIndex(R.filter); + + filterIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [0, 9] + var lastTwoFn = filterIndexed(lastTwo); + lastTwoFn([8, 6, 7, 5, 3, 0, 9]); +} + +() => { + var xs = [{a: 1}, {a: 2}, {a: 3}]; + R.find(R.propEq('a', 2))(xs); //=> {a: 2} + R.find(R.propEq('a', 4))(xs); //=> undefined +} + +() => { + var xs = [{a: 1}, {a: 2}, {a: 3}]; + R.findIndex(R.propEq('a', 2))(xs); //=> 1 + R.findIndex(R.propEq('a', 4))(xs); //=> -1 + + R.findIndex((x: number) => x === 1, [1, 2, 3]); +} + +() => { + var xs = [{a: 1, b: 0}, {a:1, b: 1}]; + R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1} + R.findLast(R.propEq('a', 4))(xs); //=> undefined +} + +() => { + var xs = [{a: 1, b: 0}, {a:1, b: 1}]; + R.findLastIndex(R.propEq('a', 1))(xs); //=> 1 + R.findLastIndex(R.propEq('a', 4))(xs); //=> -1 + R.findLastIndex((x: number) => x === 1, [1, 2, 3]); +} +() => { + var user1 = { address: { zipCode: 90210 } }; + var user2 = { address: { zipCode: 55555 } }; + var user3 = { name: 'Bob' }; + var users = [ user1, user2, user3 ]; + var isFamous = R.pathEq(['address', 'zipCode'], 90210); + R.filter(isFamous, users); //=> [ user1 ] +} +() => { + var xs: {[key:string]: string} = {a: '1', b: '0'}; + R.propEq('a', '1', xs);//=> true + R.propEq('a', '4', xs); //=> false +} +() => { + var xs: {[key:string]: number} = {a: 1, b: 0}; + R.propEq('a', 1, xs);//=> true + R.propEq('a', 4, xs); //=> false +} +() => { + var xs = {a: '1', b: '0'}; + R.propEq('a', '1', xs);//=> true + R.propEq('a', '4', xs); //=> false +} +() => { + var xs = {a: 1, b: 0}; + R.propEq('a', 1, xs);//=> true + R.propEq('a', 4, xs); //=> false +} + +interface Obj { a: number; b: number }; +() => { + var xs: Obj = {a: 1, b: 0}; + R.propEq('a', 1, xs);//=> true + R.propEq('a', 4, xs); //=> false +} + +() => { + R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]); + //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] +} + +() => { + var printXPlusFive = function(x: number) { console.log(x + 5); }; + R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3] + R.forEach(printXPlusFive)([1, 2, 3]); //=> [1, 2, 3] + //-> 6 + //-> 7 + //-> 8 +} + +() => { + var plusFive = function(num: number, idx: number, list: number[]) { list[idx] = num + 5 }; + R.addIndex(R.forEach)(plusFive)([1, 2, 3]); //=> [6, 7, 8] +} + +() => { + var byGrade = R.groupBy(function(student: {score: number; name: string}) { + var score = student.score; + return score < 65 ? 'F' : + score < 70 ? 'D' : + score < 80 ? 'C' : + score < 90 ? 'B' : 'A'; + }); + var students = [{name: 'Abby', score: 84}, + {name: 'Eddy', score: 58}, + {name: 'Jack', score: 69}]; + byGrade(students); +} + +() => { + R.groupWith(R.equals, [0, 1, 1, 2, 3, 5, 8, 13, 21]) + // [[0], [1, 1], [2, 3, 5, 8, 13, 21]] + + R.groupWith((a: number, b: number) => a % 2 === b % 2, [0, 1, 1, 2, 3, 5, 8, 13, 21]) + // [[0], [1, 1], [2], [3, 5], [8], [13, 21]] + + const isVowel = (a: string) => R.contains(a, 'aeiou') ? a : ''; + R.groupWith(R.eqBy(isVowel), 'aestiou') + // ['ae', 'st', 'iou'] +} + +() => { + R.head(['fi', 'fo', 'fum']); //=> 'fi' + R.head([10, 'ten']); // => 10 + R.head(['10', 10]); // => '10' +} + +(() => { + let list = [{id: 'xyz', title: 'A'}, {id: 'abc', title: 'B'}]; + const a1 = R.indexBy(R.prop('id'), list); + const a2 = R.indexBy(R.prop('id'))(list); + const a3 = R.indexBy<{id:string}>(R.prop('id'))(list); +}); + +() => { + R.indexOf(3, [1,2,3,4]); //=> 2 + R.indexOf(10)([1,2,3,4]); //=> -1 +} + +() => { + R.init(['fi', 'fo', 'fum']); //=> ['fi', 'fo'] +} + +() => { + R.insert(2, 5, [1,2,3,4]); //=> [1,2,5,3,4] + R.insert(2)(5, [1,2,3,4]); //=> [1,2,5,3,4] + R.insert(2, 5)([1,2,3,4]); //=> [1,2,5,3,4] +} + +() => { + R.insertAll(2, [10,11,12], [1,2,3,4]); + R.insertAll(2)([10,11,12], [1,2,3,4]); + R.insertAll(2, [10,11,12])([1,2,3,4]); +} + +() => { + var numbers = [1, 2, 3, 4]; + var transducer = R.compose(R.map(R.add(1)), R.take(2)); + + R.into([], transducer, numbers); //=> [2, 3] + + var intoArray = R.into([]); + intoArray(transducer, numbers); //=> [2, 3] +} + +() => { + var spacer = R.join(' '); + spacer(['a', 2, 3.4]); //=> 'a 2 3.4' + R.join('|', [1, 2, 3]); //=> '1|2|3' +} + +() => { + R.last(['fi', 'fo', 'fum']); //=> 'fum' +} + +() => { + R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6 + R.lastIndexOf(10, [1,2,3,4]); //=> -1 +} + +() => { + R.length([]); //=> 0 + R.length([1, 2, 3]); //=> 3 +} + +() => { + var headLens = R.lensIndex(0); + headLens([10, 20, 30, 40]); //=> 10 + headLens.set('mu', [10, 20, 30, 40]); //=> ['mu', 20, 30, 40] + R.view(headLens, ['a', 'b', 'c']); //=> 'a' + R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c'] + R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c'] +} + +() => { + var double = function(x: number) { + return x * 2; + }; + R.map(double, [1, 2, 3]); //=> [2, 4, 6] + + // functor + const stringFunctor = { + map: (fn: (c: number) => number) => { + var chars = "Ifmmp!Xpsme".split(""); + return chars.map((char) => String.fromCharCode(fn(char.charCodeAt(0)))).join(""); + } + }; + R.map((x: number) => x-1, stringFunctor); // => "Hello World" +} + +() => { + var digits = ['1', '2', '3', '4']; + var append = function(a: string, b: string): [string, string]{ + return [a + b, a + b]; + } + R.mapAccum(append, '0', digits); //=> ['01234', ['01', '012', '0123', '01234']] + R.mapAccum(append)('0', digits); //=> ['01234', ['01', '012', '0123', '01234']] + R.mapAccum(append, '0')(digits); //=> ['01234', ['01', '012', '0123', '01234']] +} + +() => { + var digits = ['1', '2', '3', '4']; + var append = function(a: string, b: string): [string, string] { + return [a + b, a + b]; + } + + R.mapAccumRight(append, '0', digits); //=> ['04321', ['04321', '0432', '043', '04']] + R.mapAccumRight(append)('0', digits); //=> ['04321', ['04321', '0432', '043', '04']] + R.mapAccumRight(append, '0')(digits); //=> ['04321', ['04321', '0432', '043', '04']] +} + +() => { + var squareEnds = function(elt: number, idx: number, list: number[]) { + if (idx === 0 || idx === list.length - 1) { + return elt * elt; + } + return elt; + }; + R.addIndex(R.map)(squareEnds, [8, 5, 3, 0, 9]); //=> [64, 5, 3, 0, 81] + R.addIndex(R.map)(squareEnds)([8, 5, 3, 0, 9]); //=> [64, 5, 3, 0, 81] +} + +() => { + R.none(R.isNaN, [1, 2, 3]); //=> true + R.none(R.isNaN, [1, 2, 3, NaN]); //=> false + R.none(R.isNaN)([1, 2, 3, NaN]); //=> false +} + +() => { + var list = ['foo', 'bar', 'baz', 'quux']; + R.nth(1, list); //=> 'bar' + R.nth(-1, list); //=> 'quux' + R.nth(-99, list); //=> undefined + R.nth(-99)(list); //=> undefined +} + +() => { + R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']); + R.partition(R.contains('s'))(['sss', 'ttt', 'foo', 'bars']); + R.partition((x: number) => x > 2, [1, 2, 3, 4]); + R.partition((x: number) => x > 2)([1, 2, 3, 4]); +} + +() => { + const a = R.pluck('a')([{a: 1}, {a: 2}]); //=> [1, 2] + const b = R.pluck(0)([[1, 2], [3, 4]]); //=> [1, 3] +} + +() => { + R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum'] + R.prepend('fee')(['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum'] +} + +() => { + R.range(1, 5); //=> [1, 2, 3, 4] + R.range(50)(53); //=> [50, 51, 52] +} + +() => { + var numbers = [1, 2, 3]; + var add = function(a: number, b: number) { + return a + b; + }; + R.reduce(add, 10, numbers); //=> 16 + R.reduce(add)(10, numbers); //=> 16 + R.reduce(add, 10)(numbers); //=> 16 +} + +interface Student { + name: string; + score: number; +} +() => { + const reduceToNamesBy = R.reduceBy((acc: string[], student: Student) => acc.concat(student.name), []); + const namesByGrade = reduceToNamesBy(function(student) { + let score = student.score; + return score < 65 ? 'F' : + score < 70 ? 'D' : + score < 80 ? 'C' : + score < 90 ? 'B' : 'A'; + }); + let students = [{name: 'Lucy', score: 92}, + {name: 'Drew', score: 85}, + {name: 'Bart', score: 62}]; + const names = namesByGrade(students); + // { + // 'A': ['Lucy'], + // 'B': ['Drew'] + // 'F': ['Bart'] + // } +} + +() => { + var reduceIndexed = R.addIndex(R.reduce); + var letters = ['a', 'b', 'c']; + var objectify = function(accObject: {[elem:string]: number}, elem: string, idx: number, list: string[]) { + accObject[elem] = idx; + return accObject; + }; + reduceIndexed(objectify, {}, letters); //=> { 'a': 0, 'b': 1, 'c': 2 } + reduceIndexed(objectify)({}, letters); //=> { 'a': 0, 'b': 1, 'c': 2 } + reduceIndexed(objectify, {})(letters); //=> { 'a': 0, 'b': 1, 'c': 2 } +} + +interface KeyValuePair extends Array { 0 : K; 1 : V; } +type Pair = KeyValuePair +() => { + var pairs: Pair[] = [ ['a', 1], ['b', 2], ['c', 3] ]; + var flattenPairs = function(acc: Pair[], pair: Pair): Pair[] { + return acc.concat(pair); + }; + R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] + R.reduceRight(flattenPairs, [])(pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] + R.reduceRight(flattenPairs)([], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] +} + +() => { + var isOdd = function(n: number) { + return n % 2 === 1; + }; + R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] + R.reject(isOdd)([1, 2, 3, 4]); //=> [2, 4] +} + +() => { + const lastTwo = function(val: number, idx: number, list: number[]) { + return list.length - idx <= 2; + }; + const rejectIndexed = R.addIndex(R.reject); + rejectIndexed(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [8, 6, 7, 5, 3] + rejectIndexed(lastTwo)([8, 6, 7, 5, 3, 0, 9]); //=> [8, 6, 7, 5, 3] +} + +() => { + R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] + R.remove(2, 3)([1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] + R.remove(2)(3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] +} + +() => { + R.repeat('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi'] + var obj = {}; + var repeatedObjs = R.repeat(obj, 5); //=> [{}, {}, {}, {}, {}] + repeatedObjs[0] === repeatedObjs[1]; //=> true +} + +() => { + R.reverse([1, 2, 3]); //=> [3, 2, 1] + R.reverse([1, 2]); //=> [2, 1] + R.reverse([1]); //=> [1] + R.reverse([]); //=> [] +} + +() => { + var numbers = [1, 2, 3, 4]; + R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24] + R.scan(R.multiply, 1)(numbers); //=> [1, 1, 2, 6, 24] + R.scan(R.multiply)(1, numbers); //=> [1, 1, 2, 6, 24] +} + +() => { + var xs = R.range(0, 10); + R.slice(2, 5, xs); //=> [2, 3, 4] + R.slice(2, 5)(xs); //=> [2, 3, 4] + R.slice(2)(5, xs); //=> [2, 3, 4] + + var str = 'Hello World'; + R.slice(2, 5, str); //=> 'llo' + R.slice(2, 5)(str); //=> 'llo' + R.slice(2)(5, str); //=> 'llo' +} + +() => { + var diff = function(a: number, b: number) { return a - b; }; + R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7] + R.sort(diff)([4,2,7,5]); //=> [2, 4, 5, 7] +} + +() => { + const fn = R.cond([ + [R.equals(0), R.always('water freezes at 0°C')], + [R.equals(100), R.always('water boils at 100°C')], + [R.T, (temp: number) => 'nothing special happens at ' + temp + '°C'] + ]); + const a: string = fn(0); //=> 'water freezes at 0°C' + const b: string = fn(50); //=> 'nothing special happens at 50°C' + const c: string = fn(100); //=> 'water boils at 100°C' +} + +() => { + R.tail(['fi', 'fo', 'fum']); //=> ['fo', 'fum'] + R.tail([1, 2, 3]); //=> [2, 3] +} + +() => { + R.take(3,[1,2,3,4,5]); //=> [1,2,3] + + var members= [ "Paul Desmond","Bob Bates","Joe Dodge","Ron Crotty","Lloyd Davis","Joe Morello","Norman Bates", + "Eugene Wright","Gerry Mulligan","Jack Six","Alan Dawson","Darius Brubeck","Chris Brubeck", + "Dan Brubeck","Bobby Militello","Michael Moore","Randy Jones"]; + var takeFive = R.take(5); + takeFive(members); //=> ["Paul Desmond","Bob Bates","Joe Dodge","Ron Crotty","Lloyd Davis"] +} +() => { + R.take(3,"Example"); //=> "Exa" + + var takeThree = R.take(3); + takeThree("Example"); //=> "Exa" +} + + + +() => { + const a: string[] = R.takeLast(1, ['foo', 'bar', 'baz']); //=> ['baz'] + const b: string[] = R.takeLast(2)(['foo', 'bar', 'baz']); //=> ['bar', 'baz'] + const c: string = R.takeLast(3, 'ramda'); //=> 'mda' + const d: string = R.takeLast(3)('ramda'); //=> 'mda' +} + +() => { + const isNotOne = (x: number) => x !== 1; + const a: number[] = R.takeLastWhile(isNotOne, [1, 2, 3, 4]); //=> [2, 3, 4] + const b: number[] = R.takeLastWhile(isNotOne)([1, 2, 3, 4]); //=> [2, 3, 4] +} + +() => { + var isNotFour = function(x: number) { + return !(x === 4); + }; + + R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3] + R.takeWhile(isNotFour)([1, 2, 3, 4]); //=> [1, 2, 3] +} + +() => { + const sayX = (x: number) => console.log('x is ' + x); + const a: number = R.tap(sayX, 100); //=> 100 +} + +() => { + const a: boolean = R.test(/^x/, 'xyz'); //=> true + const b: boolean = R.test(/^y/)('xyz'); //=> false +} + +() => { + const a1 = R.times(R.identity, 5); //=> [0, 1, 2, 3, 4] + const a2 = R.times(R.identity)(5); //=> [0, 1, 2, 3, 4] +} + +() => { + class Point { + constructor(public x: number, public y: number) { + this.x = x; + this.y = y; + } + toStringn() { + return 'new Point(' + this.x + ', ' + this.y + ')'; + } + }; + R.toString(new Point(1, 2)); //=> 'new Point(1, 2)' + + R.toString(42); //=> '42' + R.toString('abc'); //=> '"abc"' + R.toString([1, 2, 3]); //=> '[1, 2, 3]' + R.toString({foo: 1, bar: 2, baz: 3}); //=> '{"bar": 2, "baz": 3, "foo": 1}' + R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date("2001-02-03T04:05:06.000Z")' +} + +() => { + var numbers = [1, 2, 3, 4]; + var transducer = R.compose(R.map(R.add(1)), R.take(2)); + var fn = R.flip(R.append); + R.transduce(transducer, fn, [], numbers); //=> [2, 3] + R.transduce(transducer, fn, [])(numbers); //=> [2, 3] + R.transduce(transducer, fn)([], numbers); //=> [2, 3] + R.transduce(transducer)(fn, [], numbers); //=> [2, 3] +} + +() => { + const a: any[][] = R.transpose([[1, 'a'], [2, 'b'], [3, 'c']]) //=> [[1, 2, 3], ['a', 'b', 'c']] + const b: any[][] = R.transpose([[1, 2, 3], ['a', 'b', 'c']]) //=> [[1, 'a'], [2, 'b'], [3, 'c']] + const c: any[][] = R.transpose([[10, 11], [20], [], [30, 31, 32]]) //=> [[10, 20, 30], [11, 31], [32]] +} + +() => { + const x = R.prop('x'); + const a: boolean = R.tryCatch(R.prop('x'), R.F, {x: true}); //=> true + const b: boolean = R.tryCatch(R.prop('x'), R.F, null); //=> false +} + +() => { + R.uniq([1, 1, 2, 1]); //=> [1, 2] + R.uniq([{}, {}]); //=> [{}, {}] + R.uniq([1, '1']); //=> [1, '1'] +} + +() => { + var strEq = function(a: any, b: any) { return String(a) === String(b); }; + R.uniqWith(strEq, [1, '1', 2, 1]); //=> [1, 2] + R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2] + R.uniqWith(strEq)([{}, {}]); //=> [{}] + R.uniqWith(strEq)([1, '1', 1]); //=> [1] + R.uniqWith(strEq)(['1', 1, 1]); //=> ['1'] +} + +() => { + R.equals(R.unnest([1, [2], [[3]]]), [1,2,[3]]); //=> true + R.equals(R.unnest([[1, 2], [3, 4], [5, 6]]),[1,2,3,4,5,6]); //=> true +} + +() => { + R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] + R.xprod([1, 2])(['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] +} + +() => { + R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']] + R.zip([1, 2, 3])(['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']] +} + +() => { + R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3} + R.zipObj(['a', 'b', 'c'])([1, 2, 3]); //=> {a: 1, b: 2, c: 3} +} + +() => { + var f = function(x:number, y:string) { + // ... + }; + R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']); //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] + R.zipWith(f)([1, 2, 3], ['a', 'b', 'c']); //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] + R.zipWith(f, [1, 2, 3])(['a', 'b', 'c']); //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] +} + +/***************************************************************** + * Object category + */ +() => { + const a = R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} + const b = R.assoc('c')(3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} + const c = R.assoc('c', 3)({a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} +} + +() => { + const a1 = R.dissoc<{a:number, c:number}>('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} + const a2 = R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} + const a4 = R.dissoc('b')<{a:number, c:number}>({a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} +} + +() => { + const a = R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} + const b = R.assocPath(['a', 'b', 'c'])(42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} + const c = R.assocPath(['a', 'b', 'c'], 42)({a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} +} + +() => { + const a1 = R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}} + // optionally specify return type + const a2 = R.dissocPath<{a :{ b: number}}>(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}} + const a3 = R.dissocPath(['a', 'b', 'c'])({a: {b: {c: 42}}}); //=> {a: {b: {}}} +} + +() => { + var obj1 = [{}, {}, {}]; + var obj2 = [{a:1}, {a:2}, {a:3}]; + const a1: any[] = R.clone(obj1); + const a2: {a: number}[] = R.clone(obj2); + const a3: any = R.clone({}); + const a4: number = R.clone(10); + const a5: string = R.clone('foo'); + const a6: number = R.clone(Date.now()); +} + +() => { + var o1 = { a: 1, b: 2, c: 3, d: 4 }; + var o2 = { a: 10, b: 20, c: 3, d: 40 }; + const a1 = R.eqProps('a', o1, o2); //=> false + const a2 = R.eqProps('c', o1, o2); //=> true + const a3: {(obj1: T, obj2: U): boolean} = R.eqProps('c'); + const a4: {(obj2: U): boolean} = R.eqProps('c', o1); +} + +() => { + const a1 = R.evolve({ elapsed: R.add(1), remaining: R.add(-1) }, { name: 'Tomato', elapsed: 100, remaining: 1400 }); + const a2 = R.evolve({ elapsed: R.add(1), remaining: R.add(-1) })({ name: 'Tomato', elapsed: 100, remaining: 1400 }); +} + +() => { + // var tomato = {firstName: 'Tomato ', data: {elapsed: 100, remaining: 1400}, id:123}; + // var transformations = { + // firstName: R.trim, + // lastName: R.trim, // Will not get invoked. + // data: {elapsed: R.add(1), remaining: R.add(-1)} + // }; + // const a = R.evolve(transformations, tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123} + // const b = R.evolve(transformations)(tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123} +} + +() => { + const hasName = R.has('name'); + const a1: boolean = hasName({name: 'alice'}); //=> true + const a2: boolean = hasName({name: 'bob'}); //=> true + const a3: boolean = hasName({}); //=> false + + const point = {x: 0, y: 0}; + const pointHas = R.flip(R.has)(point); + const b1: boolean = pointHas('x'); //=> true + const b2: boolean = pointHas('y'); //=> true + const b3: boolean = pointHas('z'); //=> false +} + +class Rectangle { + constructor(public width: number, public height: number) { + this.width = width; + this.height = height; + } + area():number { + return this.width * this.height; + } +}; +() => { + + var square = new Rectangle(2, 2); + R.hasIn('width', square); //=> true + R.hasIn('area', square); //=> true + R.flip(R.hasIn)(square)('area'); //=> true +} + +() => { + var raceResultsByFirstName = { + first: 'alice', + second: 'jake', + third: 'alice', + }; + R.invert(raceResultsByFirstName); + //=> { 'alice': ['first', 'third'], 'jake':['second'] } +} + +() => { + let raceResults0 = { + first: 'alice', + second: 'jake' + }; + R.invertObj(raceResults0); + //=> { 'alice': 'first', 'jake':'second' } + + // Alternatively: + let raceResults1 = ['alice', 'jake']; + R.invertObj(raceResults1); + //=> { 'alice': '0', 'jake':'1' } +} + +() => { + R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] +} + +() => { + var f = new F(); + R.keysIn(f); //=> ['x', 'y'] +} + +() => { + var xLens = R.lens(R.prop('x'), R.assoc('x')); + R.view(xLens, {x: 1, y: 2}); //=> 1 + R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} + R.set(xLens)(4, {x: 1, y: 2}); //=> {x: 4, y: 2} + R.set(xLens, 4)({x: 1, y: 2}); //=> {x: 4, y: 2} + R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} + R.over(xLens, R.negate)({x: 1, y: 2}); //=> {x: -1, y: 2} + R.over(xLens)(R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} +} +() => { + var headLens = R.lensIndex(0); + R.view(headLens, ['a', 'b', 'c']); //=> 'a' + R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c'] + R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c'] +} +() => { + var xLens = R.lensProp('x'); + R.view(xLens, {x: 1, y: 2}); //=> 1 + R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} + R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} +} + +() => { + const xyLens = R.lensPath(['x', 'y']); + + R.view(xyLens, {x: {y: 2, z: 3}}); //=> 2 + R.set(xyLens, 4, {x: {y: 2, z: 3}}); //=> {x: {y: 4, z: 3}} + R.over(xyLens, R.negate, {x: {y: 2, z: 3}}); //=> {x: {y: -2, z: 3}} +} + +() => { + R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] +} + +() => { + var f = new F(); + R.keysIn(f); //=> ['x', 'y'] +} + +() => { + var headLens = R.lens( + function get(arr: number[]) { return arr[0]; }, + function set(val: number, arr: number[]) { return [val].concat(arr.slice(1)); } + ); + headLens([10, 20, 30, 40]); //=> 10 + headLens.set('mu', [10, 20, 30, 40]); //=> ['mu', 20, 30, 40] + + var phraseLens = R.lens( + function get(obj: any) { return obj.phrase; }, + function set(val: string, obj: any) { + var out = R.clone(obj); + out.phrase = val; + return out; + } + ); + var obj1 = { phrase: 'Absolute filth . . . and I LOVED it!'}; + var obj2 = { phrase: "What's all this, then?"}; + phraseLens(obj1); // => 'Absolute filth . . . and I LOVED it!' + phraseLens(obj2); // => "What's all this, then?" + phraseLens.set('Ooh Betty', obj1); //=> { phrase: 'Ooh Betty'} +} + + +() => { + var phraseLens = R.lensProp('phrase'); + var obj1 = { phrase: 'Absolute filth . . . and I LOVED it!'}; + var obj2 = { phrase: "What's all this, then?"}; + phraseLens(obj1); // => 'Absolute filth . . . and I LOVED it!' + phraseLens(obj2); // => "What's all this, then?" + phraseLens.set('Ooh Betty', obj1); //=> { phrase: 'Ooh Betty'} +} + +() => { + R.merge({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); + //=> { 'name': 'fred', 'age': 40 } + + var resetToDefault = R.flip(R.merge)({x: 0}); + resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2} +} + +() => { + const a = R.mergeAll([{foo:1},{bar:2},{baz:3}]); //=> {foo:1,bar:2,baz:3} + const b = R.mergeAll([{foo:1},{foo:2},{bar:2}]); //=> {foo:2,bar:2} +} + +() => { + const a = R.mergeWith(R.concat, + { a: true, values: [10, 20] }, + { b: true, values: [15, 35] }); + //=> { a: true, b: true, values: [10, 20, 15, 35] } +} + +() => { + let concatValues = (k:string, l: string, r: string) => k == 'values' ? R.concat(l, r) : r; + R.mergeWithKey(concatValues, + { a: true, thing: 'foo', values: [10, 20] }, + { b: true, thing: 'bar', values: [15, 35] }); + const merge = R.mergeWithKey(concatValues); + merge({ a: true, thing: 'foo', values: [10, 20] }, { b: true, thing: 'bar', values: [15, 35] }); +} + +() => { + const a1 = R.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2 + const a2 = R.pathOr('N/A', ['a', 'b'])({a: {b: 2}}); //=> 2 + const a3 = R.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A" + const a4 = R.pathOr({c:2})(['a', 'b'], {c: {b: 2}}); //=> "N/A" +} + +() => { + var isPositive = function(n: number) { + return n > 0; + }; + const a1 = R.pickBy(isPositive, {a: 1, b: 2, c: -1, d: 0, e: 5}); //=> {a: 1, b: 2, e: 5} + var containsBackground = function(val: any) { + return val.bgcolor; + }; + var colors = {1: {color: 'read'}, 2: {color: 'black', bgcolor: 'yellow'}}; + R.pickBy(containsBackground, colors); //=> {2: {color: 'black', bgcolor: 'yellow'}} + + var isUpperCase = function(val: number, key: string) { return key.toUpperCase() === key; } + R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4} +} + + +() => { + const a1 = R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + const a2 = R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1} + const a3 = R.pick(['a', 'e', 'f'])({a: 1, b: 2, c: 3, d: 4}); //=> {a: 1} + const a4 = R.pick(['a', 'e', 'f'], [1, 2, 3, 4]); //=> {a: 1} +} + +() => { + var matchPhrases = R.compose( + R.objOf('must'), + R.map(R.objOf('match_phrase')) +) + +matchPhrases(['foo', 'bar', 'baz']); +} +() => { + R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3} + R.omit(['a', 'd'])({a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3} +} + + +() => { + R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3} +} + +() => { + R.pair('foo', 'bar'); //=> ['foo', 'bar'] + let p = R.pair('foo', 1); //=> ['foo', 'bar'] + let x: string = p[0]; + let y: number = p[1]; +} + +() => { + var headLens = R.lensIndex(0); + R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']); //=> ['FOO', 'bar', 'baz'] +} + +() => { + R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + R.pickAll(['a', 'd'])({a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined} + R.pickAll(['a', 'e', 'f'])({a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined} +} + +() => { + var isUpperCase = function(val: number, key: string) { return key.toUpperCase() === key; } + R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4} +} + +() => { + var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2}; + var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7}; + var kids = [abby, fred]; + R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}] +} + +() => { + var x: number = R.prop('x', {x: 100}); //=> 100 + const a = R.prop('x', {}); //=> undefined +} + +() => { + var alice = { + name: 'ALICE', + age: 101 + }; + var favorite = R.prop('favoriteLibrary'); + var favoriteWithDefault = R.propOr('Ramda', 'favoriteLibrary'); + + const s1 = favorite(alice); //=> undefined + const s2 = favoriteWithDefault(alice); //=> 'Ramda' +} + +() => { + const a: boolean = R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true + const b: boolean = R.propSatisfies(x => x > 0, 'x')({x: 1, y: 2}); //=> true + const c: boolean = R.propSatisfies(x => x > 0)('x')({x: 1, y: 2}); //=> true +} + +() => { + R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2] + R.props(['c', 'a', 'b'], {b: 2, a: 1}); //=> [undefined, 1, 2] + + var fullName = R.compose(R.join(' '), R.props(['first', 'last'])); + fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth' +} + +() => { + const a = R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]] +} + +() => { + var f = new F(); + const a1 = R.toPairsIn(f); //=> [['x','X'], ['y','Y']] + const a2 = R.toPairsIn(f); //=> [['x','X'], ['y','Y']] +} + +() => { + const a = R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3] +} +() => { + var f = new F(); + const a = R.valuesIn(f); //=> ['X', 'Y'] +} + +() => { + var spec = {x: 2}; + var x1: boolean = R.where(spec, {w: 10, x: 2, y: 300}); //=> true + var x2: boolean = R.where(spec, {x: 1, y: 'moo', z: true}); //=> false + var x3: boolean = R.where(spec)({w: 10, x: 2, y: 300}); //=> true + var x4: boolean = R.where(spec)({x: 1, y: 'moo', z: true}); //=> false + + // There's no way to represent the below functionality in typescript + // per http://stackoverflow.com/a/29803848/632495 + // will need a work around. + + var spec2 = {x: function(val: number, obj: any) { return val + obj.y > 10; }}; + R.where(spec2, {x: 2, y: 7}); //=> false + R.where(spec2, {x: 3, y: 8}); //=> true + + var xs = [{x: 2, y: 1}, {x: 10, y: 2}, {x: 8, y: 3}, {x: 10, y: 4}]; + R.filter(R.where({x: 10}), xs); // ==> [{x: 10, y: 2}, {x: 10, y: 4}] + R.filter(R.where({x: 10}))(xs); // ==> [{x: 10, y: 2}, {x: 10, y: 4}] +} + +() => { + // pred :: Object -> Boolean + var pred = R.whereEq({a: 1, b: 2}); + pred({a: 1}); //=> false + pred({a: 1, b: 2}); //=> true + pred({a: 1, b: 2, c: 3}); //=> true + pred({a: 1, b: 1}); //=> false + R.whereEq({a: 'one'}, {a: 'one'}); // => true +} + +() => { + const a: number[] = R.without([1, 2], [1, 2, 1, 3, 4]); //=> [3, 4] +} + +() => { + var mapIndexed = R.addIndex(R.map); + mapIndexed(function(val: string, idx: number) {return idx + '-' + val;})(['f', 'o', 'o', 'b', 'a', 'r']); + //=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r'] + mapIndexed((rectangle: Rectangle, idx: number):number => rectangle.area()*idx, [new Rectangle(1,2), new Rectangle(4,7)]); + //=> [2, 56] +} + +() => { + var reduceIndexed = R.addIndex(R.reduce); + reduceIndexed(function(acc: string, val: string, idx: number) { + return acc + ',' + idx + '-' + val; + } + ,'' + ,['f', 'o', 'o', 'b', 'a', 'r']); + //=> ['0-f,1-o,2-o,3-b,4-a,5-r'] +} + + + +() => { + var t = R.always('Tee'); + const x: string = t(); //=> 'Tee' +} + +() => { + const x: number[] = R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6] + const y: number[] = R.ap([R.multiply(2), R.add(3)])([1,2,3]); //=> [2, 4, 6, 4, 5, 6] +} + +() => { + var nums = [1, 2, 3, -99, 42, 6, 7]; + R.apply(Math.max, nums); //=> 42 + R.apply(Math.max)(nums); //=> 42 +} + +() => { + type T = {sum: number, nested: {mul: number}}; + const getMetrics = R.applySpec({ + sum: R.add, nested: { mul: R.multiply } + }); + const result = getMetrics(2, 4); // => { sum: 6, nested: { mul: 8 } } +} + +() => { + var takesThreeArgs = function(a: number, b: number, c: number) { + return [a, b, c]; + }; + takesThreeArgs.length; //=> 3 + takesThreeArgs(1, 2, 3); //=> [1, 2, 3] + + var takesTwoArgs = R.binary(takesThreeArgs); + takesTwoArgs.length; //=> 2 + // Only 2 arguments are passed to the wrapped function + takesTwoArgs(1, 2, 3); //=> [1, 2, undefined] +} + +() => { + var indentN = R.pipe(R.times(R.always(' ')), + R.join(''), + R.replace(/^(?!$)/gm) + ); + + var format = R.converge( + R.call, [ + R.pipe(R.prop('indent'), indentN), + R.prop('value') + ] + ); + + format({indent: 2, value: 'foo\nbar\nbaz\n'}); //=> ' foo\n bar\n baz\n' +} + +() => { + type T = {age: number}; + var cmp = R.comparator(function(a: T, b: T) { + return a.age < b.age; + }); + var people = [ + {name: 'Agy', age:33}, {name: 'Bib', age: 15}, {name: 'Cari', age: 16} + ]; + R.sort(cmp, people); +} + +() => { + var add = function(a: number, b: number) { return a + b; }; + var multiply = function(a: number, b: number) { return a * b; }; + var subtract = function(a: number, b: number) { return a - b; }; + + //≅ multiply( add(1, 2), subtract(1, 2) ); + const x: number = R.converge(multiply, [ add, subtract ])(1, 2); //=> -3 + + var add3 = function(a: number, b: number, c: number) { return a + b + c; }; + const y: number = R.converge(add3, [ multiply, add, subtract ])(1, 2); //=> 4 +} + +() => { + const f0 = R.compose(Math.pow); + const f1 = R.compose(R.negate, Math.pow); + const f2 = R.compose(R.inc, R.negate, Math.pow); + const f3 = R.compose(R.inc, R.inc, R.negate, Math.pow); + const f4 = R.compose(R.inc, R.inc, R.inc, R.negate, Math.pow); + const f5 = R.compose(R.inc, R.inc, R.inc, R.inc, R.negate, Math.pow); + const x0: number = f0(3, 4); // -(3^4) + 1 + const x1: number = f1(3, 4); // -(3^4) + 1 + const x2: number = f2(3, 4); // -(3^4) + 1 + const x3: number = f3(3, 4); // -(3^4) + 1 + const x4: number = f4(3, 4); // -(3^4) + 1 + const x5: number = f5(3, 4); // -(3^4) + 1 +} + +() => { + const fn = function(a: string, b: number, c: string) { + return [a,b,c]; + } + const gn = R.compose(R.length, fn); + const x: number = gn('Hello', 4, "world"); +} + +(() => { + var Circle = function(r: number) { + this.r = r; + this.colors = Array.prototype.slice.call(arguments, 1); + }; + Circle.prototype.area = function() {return Math.PI * Math.pow(this.r, 2);}; + var circleN = R.constructN(2, Circle); + var c1 = circleN(1, 'red'); + var circle = R.construct(Circle); + var c1 = circle(1, 'red'); +})(); + +/***************************************************************** + * Relation category + */ + +() => { + var numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2]; + var letters = R.split('', 'abcABCaaaBBc'); + R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1} + R.countBy(R.toLower)(letters); //=> {'a': 5, 'b': 4, 'c': 3} +} + +() => { + R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2] + R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5] +} + +() => { + function cmp(x: any, y: any) { return x.a === y.a; } + var l1 = [{a: 1}, {a: 2}, {a: 3}]; + var l2 = [{a: 3}, {a: 4}]; + R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}] +} + +() => { + R.equals(1, 1); //=> true + R.equals('2', '1'); //=> false + R.equals([1, 2, 3], [1, 2, 3]); //=> true + + var a: any = {}; a.v = a; + var b: any = {}; b.v = b; + R.equals(a, b); //=> true +} + +() => { + const a1 = R.identity(1); //=> 1 + let obj = {}; + const a2 = R.identity([1,2,3]); + const a3 = R.identity(['a','b','c']); + const a4 = R.identity(obj) === obj; //=> true +} + +() => { + var o = {}; + R.identical(o, o); //=> true + R.identical(1, 1); //=> true + R.identical('2', '1'); //=> false + R.identical([], []); //=> false + R.identical(0, -0); //=> false + R.identical(NaN, NaN); //=> true +} + +() => { + R.path(['a', 'b'], {a: {b: 2}}); //=> 2 + R.path(['a', 'b'])({a: {b: 2}}); //=> 2 +} + +() => { + var sortByNameCaseInsensitive = R.sortBy(R.compose(R.toLower, R.prop('name'))); + var alice = { + name: 'ALICE', + age: 101 + }; + var bob = { + name: 'Bob', + age: -10 + }; + var clara = { + name: 'clara', + age: 314.159 + }; + var people = [clara, bob, alice]; + sortByNameCaseInsensitive(people); //=> [alice, bob, clara] +} + +() => { + const a: number[][] = R.splitAt(1, [1, 2, 3]); //=> [[1], [2, 3]] + const b: number[][] = R.splitAt(1)([1, 2, 3]); //=> [[1], [2, 3]] + const c: string[] = R.splitAt(5, 'hello world'); //=> ['hello', ' world'] + const d: string[] = R.splitAt(-1, 'foobar'); //=> ['fooba', 'r'] +} + +() => { + const a: number[][] = R.splitWhen(R.equals(2), [1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]] + const b: number[][] = R.splitWhen(R.equals(2))([1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]] +} + +() => { + R.add(2, 3); //=> 5 + R.add(7)(10); //=> 17 + R.add("Hello", " World"); //=> "Hello World" + R.add("Hello")(" World"); //=> "Hello World" +} + +() => { + R.dec(42); //=> 41 +} + +() => { + R.divide(71, 100); //=> 0.71 + + var half = R.flip(R.divide)(2); + half(42); //=> 21 + + var reciprocal = R.divide(1); + reciprocal(4); //=> 0.25 +} + +() => { + R.gt(2, 6); //=> false + R.gt(2, 0); //=> true + R.gt(2, 2); //=> false + R.flip(R.gt)(2)(10); //=> true + R.gt(2)(10); //=> false +} + +() => { + R.gte(2, 6); //=> false + R.gte(2, 0); //=> true + R.gte(2, 2); //=> false + R.flip(R.gte)(2)(10); //=> true + R.gte(2)(10); //=> false +} + +() => { + R.isNaN(NaN); //=> true + R.isNaN(undefined); //=> false + R.isNaN({}); //=> false +} + +() => { + R.lt(2, 6); //=> true + R.lt(2, 0); //=> false + R.lt(2, 2); //=> false + R.lt(5)(10); //=> true + R.flip(R.lt)(5)(10); //=> false // right-sectioned currying +} + +() => { + R.lte(2, 6); //=> true + R.lte(2, 0); //=> false + R.lte(2, 2); //=> true + R.flip(R.lte)(2)(1); //=> true + R.lte(2)(10); //=> true +} + +() => { + R.mathMod(-17, 5); //=> 3 + R.mathMod(17, 5); //=> 2 + R.mathMod(17, -5); //=> NaN + R.mathMod(17, 0); //=> NaN + R.mathMod(17.2, 5); //=> NaN + R.mathMod(17, 5.3); //=> NaN + + var clock = R.flip(R.mathMod)(12); + clock(15); //=> 3 + clock(24); //=> 0 + + var seventeenMod = R.mathMod(17); + seventeenMod(3); //=> 2 +} + +() => { + var hasName = R.has('name'); + hasName({name: 'alice'}); //=> true + hasName({name: 'bob'}); //=> true + hasName({}); //=> false + + var point = {x: 0, y: 0}; + var pointHas = R.flip(R.has)(point); + pointHas('x'); //=> true + pointHas('y'); //=> true + pointHas('z'); //=> false +} + +() => { + let x: R.Ord = R.max(7, 3); //=> 7 + let y: R.Ord = R.max('a', 'z'); //=> 'z' +} + +() => { + function cmp(obj: { x: R.Ord }) { return obj.x; } + var a = {x: 1}, b = {x: 2}, c = {x: 3}, d = {x: "a"}, e = {x:"z"}; + R.maxBy(cmp, a, c); //=> {x: 3} + R.maxBy(cmp)(a, c); //=> {x: 3} + R.maxBy(cmp)(a)(b); + R.maxBy(cmp)(d)(e); +} + +() => { + const a: number = R.mean([2, 7, 9]); //=> 6 + const b: number = R.mean([]); //=> NaN +} + +() => { + const a: number = R.median([7, 2, 10, 9]); //=> 8 + const b: number = R.median([]); //=> NaN +} + +() => { + let x: R.Ord = R.min(9, 3); //=> 3 + let y: R.Ord = R.min('a', 'z'); //=> 'a' +} + +() => { + function cmp(obj: {x: R.Ord}) { return obj.x; } + var a = {x: 1}, b = {x: 2}, c = {x: 3}, d = {x: "a"}, e = {x: "z"}; + R.minBy(cmp, a, b); //=> {x: 1} + R.minBy(cmp)(a, b); //=> {x: 1} + R.minBy(cmp)(a)(c); + R.minBy(cmp, d, e); +} + +() => { + R.modulo(17, 3); //=> 2 + // JS behavior: + R.modulo(-17, 3); //=> -2 + R.modulo(17, -3); //=> 2 + + var isOdd = R.flip(R.modulo)(2); + isOdd(42); //=> 0 + isOdd(21); //=> 1 +} + +() => { + var double = R.multiply(2); + var triple = R.multiply(3); + double(3); //=> 6 + triple(4); //=> 12 + R.multiply(2, 5); //=> 10 +} + +() => { + R.negate(42); //=> -42 +} + +() => { + R.product([2,4,6,8,100,1]); //=> 38400 +} + +() => { + R.subtract(10, 8); //=> 2 + + var minus5 = R.flip(R.subtract)(5); + minus5(17); //=> 12 + + var complementaryAngle = R.subtract(90); + complementaryAngle(30); //=> 60 + complementaryAngle(72); //=> 18 +} + +() => { + R.sum([2,4,6,8,100,1]); //=> 121 +} + +() => { + const a: number[] = R.symmetricDifference([1,2,3,4], [7,6,5,4,3]); //=> [1,2,7,6,5] + const b: number[] = R.symmetricDifference([7,6,5,4,3])([1,2,3,4]); //=> [7,6,5,1,2] +} + +() => { + const eqA = R.eqBy(R.prop('a')); + const l1 = [{a: 1}, {a: 2}, {a: 3}, {a: 4}]; + const l2 = [{a: 3}, {a: 4}, {a: 5}, {a: 6}]; + R.symmetricDifferenceWith(eqA, l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] + R.symmetricDifferenceWith(eqA)(l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] + const c: (a: any[]) => any[] = R.symmetricDifferenceWith(eqA)(l1); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] +} + +/***************************************************************** + * String category + */ + +() => { + R.replace('foo', 'bar', 'foo foo foo'); //=> 'bar foo foo' + R.replace('foo', 'bar')('foo foo foo'); //=> 'bar foo foo' + R.replace('foo')('bar')('foo foo foo'); //=> 'bar foo foo' + R.replace(/foo/, 'bar', 'foo foo foo'); //=> 'bar foo foo' + + // Use the "g" (global) flag to replace all occurrences: + R.replace(/foo/g, 'bar', 'foo foo foo'); //=> 'bar bar bar' + R.replace(/foo/g, 'bar')('foo foo foo'); //=> 'bar bar bar' + R.replace(/foo/g)('bar')('foo foo foo'); //=> 'bar bar bar' +} + +/***************************************************************** + * Is category + */ + +() => { + R.is(Object, {}); //=> true + R.is(Object)({}); //=> true + R.is(Number, 1); //=> true + R.is(Number)(1); //=> true + R.is(Object, 1); //=> false + R.is(Object)(1); //=> false + R.is(String, 's'); //=> true + R.is(String)('s'); //=> true + R.is(String, new String('')); //=> true + R.is(String)(new String('')); //=> true + R.is(Object, new String('')); //=> true + R.is(Object)(new String('')); //=> true + R.is(Object, 's'); //=> false + R.is(Object)('s'); //=> false + R.is(Number, {}); //=> false + R.is(Number)({}); //=> false +} + +/***************************************************************** + * Logic category + */ +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0}; + var f = R.allPass([gt10, even]); + f(11); //=> false + f(12); //=> true +} + +() => { + R.and(false, true); //=> false + R.and(0, []); //=> 0 + R.and(0)([]); //=> 0 + R.and(null, ''); //=> null + var Why: any = (function(val: boolean) { + var why: any; + why.val = val; + why.and = function(x: boolean) { + return this.val && x; + } + return Why; + })(true); + var why = new Why(true); + R.and(why, false); // false +} +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0}; + var f = R.anyPass([gt10, even]); + f(11); //=> true + f(8); //=> true + f(9); //=> false +} + +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0 }; + var f = R.both(gt10, even); + var g = R.both(gt10)(even); + f(100); //=> true + f(101); //=> false +} +() => { + var isEven = function(n: number) { return n % 2 === 0; }; + var isOdd = R.complement(isEven); + isOdd(21); //=> true + isOdd(42); //=> false +} + +(() => { + R.eqBy(Math.abs, 5, -5); //=> true +}); + +() => { + var defaultTo42 = R.defaultTo(42); + defaultTo42(null); //=> 42 + defaultTo42(undefined); //=> 42 + defaultTo42('Ramda'); //=> 'Ramda' +} +() => { + var gt10 = function(x: number) { return x > 10; }; + var even = function(x: number) { return x % 2 === 0 }; + var f = R.either(gt10, even); + var g = R.either(gt10)(even); + f(101); //=> true + f(8); //=> true +} +() => { + // Flatten all arrays in the list but leave other values alone. + var flattenArrays = R.map(R.ifElse(Array.isArray, R.flatten, R.identity)); + + flattenArrays([[0], [[10], [8]], 1234, {}]); //=> [[0], [10, 8], 1234, {}] + flattenArrays([[[10], 123], [8, [10]], "hello"]); //=> [[10, 123], [8, 10], "hello"] +} +() => { + R.isEmpty([1, 2, 3]); //=> false + R.isEmpty([]); //=> true + R.isEmpty(''); //=> true + R.isEmpty(null); //=> false + R.isEmpty({}); //=>true + R.isEmpty({a:1}); //=> false +} + +() => { + R.not(true); //=> false + R.not(false); //=> true + R.not(0); // => true + R.not(1); // => false +} + +class Why { + val: boolean; + constructor(val: boolean) { + this.val = val; + } + or(x: boolean) { + return this.val && x; + } +} +() => { + const x0: boolean = R.or(false, true); //=> false + const x1: number|any[] = R.or(0, []); //=> [] + const x2: number|any[] = R.or(0)([]); //=> [] + const x3: string = R.or(null, ''); //=> '' + + var why = new Why(true); + why.or(true) + const x4: Why|boolean = R.or(why, false); // false +} + +() => { + R.intersperse(',', ['foo', 'bar']); //=> ['foo', ',', 'bar'] + R.intersperse(0, [1, 2]); //=> [1, 0, 2] + R.intersperse(0, [1]); //=> [1] +} diff --git a/ramda/ramda.d.ts b/ramda/ramda.d.ts new file mode 100644 index 0000000000..7ed44bf148 --- /dev/null +++ b/ramda/ramda.d.ts @@ -0,0 +1,1807 @@ +// Type definitions for ramda (www.ramdajs.com) 0.21.0 +// Project: https://github.com/donnut/typescript-ramda +// Definitions by: Erwin Poeze +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var R: R.Static; + +declare namespace R { + type Ord = number | string | boolean; + + interface ListIterator { + (value: T, index: number, list: T[]): TResult; + } + + interface Functor { + map(a: any): T; + } + + interface ObjectIterator { + (element: T, key: string, obj: Dictionary): Dictionary; + } + + interface KeyValuePair extends Array { 0 : K; 1 : V; } + + interface ArrayLike { + nodeType: number; + } + + interface Arity0Fn { + (): any + } + + interface Arity1Fn { + (a: any): any + } + + interface Arity2Fn { + (a: any, b: any): any + } + + interface ObjFunc { + [index:string]: Function; + } + + interface ObjFunc2 { + [index:string]: (x: any, y: any) => boolean; + } + + interface Pred { + (...a: any[]): boolean; + } + + interface ObjPred { + (value: any, key: string): boolean; + } + + interface Dictionary { + [index: string]: T; + } + + interface CharList extends String { + push(x: string): void; + } + + interface Nested { + [index: string]: Nested|{(value: any): U}; + } + + interface Lens { + (obj: T): U; + set(str: string, obj: T): U; + } + + // @see https://gist.github.com/donnut/fd56232da58d25ceecf1, comment by @albrow + interface CurriedFunction2 { + (t1: T1): (t2: T2) => R; + (t1: T1, t2: T2): R; + } + + interface CurriedFunction3 { + (t1: T1): CurriedFunction2; + (t1: T1, t2: T2): (t3: T3) => R; + (t1: T1, t2: T2, t3: T3): R; + } + + interface CurriedFunction4 { + (t1: T1): CurriedFunction3; + (t1: T1, t2: T2): CurriedFunction2; + (t1: T1, t2: T2, t3: T3): (t4: T4) => R; + (t1: T1, t2: T2, t3: T3, t4: T4): R; + } + + interface CurriedFunction5 { + (t1: T1): CurriedFunction4; + (t1: T1, t2: T2): CurriedFunction3; + (t1: T1, t2: T2, t3: T3): CurriedFunction2; + (t1: T1, t2: T2, t3: T3, t4: T4): (t5: T5) => R; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): R; + } + + interface CurriedFunction6 { + (t1: T1): CurriedFunction5; + (t1: T1, t2: T2): CurriedFunction4; + (t1: T1, t2: T2, t3: T3): CurriedFunction3; + (t1: T1, t2: T2, t3: T3, t4: T4): CurriedFunction2; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): (t6: T6) => R; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6): R; + } + + interface Reduced {} + + interface Static { + + /** + * Adds two numbers (or strings). Equivalent to a + b but curried. + */ + add(a: number, b: number): number; + add(a: string, b: string): string; + add(a: number): (b: number) => number; + add(a: string): (b: string) => string; + + /** + * Creates a new list iteration function from an existing one by adding two new parameters to its callback + * function: the current index, and the entire list. + */ + addIndex(fn: (f: (item: T) => U, list: T[]) => U[] ) + : CurriedFunction2<(item: T, idx: number, list?: T[]) => U, T[], U[]>; + /* Special case for forEach */ + addIndex(fn: (f: (item: T) => void, list: T[]) => T[]) + : CurriedFunction2<(item: T, idx: number, list?: T[]) => void, T[], T[]>; + /* Special case for reduce */ + addIndex(fn: (f: (acc:U, item: T) => U, aci:U, list: T[]) => U) + : CurriedFunction3<(acc:U, item: T, idx: number, list?: T[]) => U, U, T[], U>; + + /** + * Applies a function to the value at the given index of an array, returning a new copy of the array with the + * element at the given index replaced with the result of the function application. + */ + adjust(fn: (a: T) => T, index: number, list: T[]): T[]; + adjust(fn: (a: T) => T, index: number): (list: T[]) => T[]; + + /** + * Returns true if all elements of the list match the predicate, false if there are any that don't. + */ + all(fn: (a: T) => boolean, list: T[]): boolean; + all(fn: (a: T) => boolean): (list: T[]) => boolean; + + /** + * Given a list of predicates, returns a new predicate that will be true exactly when all of them are. + */ + allPass(preds: Pred[]): Pred; + + /** + * Returns a function that always returns the given value. + */ + always(val: T): () => T; + + + /** + * A function that returns the first argument if it's falsy otherwise the second argument. Note that this is + * NOT short-circuited, meaning that if expressions are passed they are both evaluated. + */ + and(fn1: T, val2: boolean|any): boolean; + and(fn1: T): (val2: boolean|any) => boolean; + + /** + * Returns true if at least one of elements of the list match the predicate, false otherwise. + */ + any(fn: (a: T) => boolean, list: T[]): boolean; + any(fn: (a: T) => boolean): (list: T[]) => boolean; + + /** + * Given a list of predicates returns a new predicate that will be true exactly when any one of them is. + */ + anyPass(preds: Pred[]): Pred; + + /** + * ap applies a list of functions to a list of values. + */ + ap(fns: ((a: T) => U)[], vs: T[]): U[]; + ap(fns: ((a: T) => U)[]): (vs: T[]) => U[]; + + + /** + * Returns a new list, composed of n-tuples of consecutive elements If n is greater than the length of the list, + * an empty list is returned. + */ + aperture(n: number, list: T): T[][]; + aperture(n: number): (list: T) => T[][]; + + /** + * Returns a new list containing the contents of the given list, followed by the given element. + */ + append(el: U, list: T[]): (T & U)[]; + append(el: U): (list: T[]) => (T & U)[]; + append(el: U): (list: T[]) => (T & U)[]; + + /** + * Applies function fn to the argument list args. This is useful for creating a fixed-arity function from + * a variadic function. fn should be a bound function if context is significant. + */ + apply(fn: (arg0: T, ...args: T[]) => TResult, args: U[]): TResult; + apply(fn: (arg0: T, ...args: T[]) => TResult): (args: U[]) => TResult; + + /** + * Given a spec object recursively mapping properties to functions, creates a function producing an object + * of the same structure, by mapping each property to the result of calling its associated function with + * the supplied arguments. + */ + applySpec(obj: any): (...args: any[]) => T; + + /** + * Makes a shallow clone of an object, setting or overriding the specified property with the given value. + */ + assoc(prop: string, val: T, obj: U): {prop: T} & U; + assoc(prop: string): (val: T, obj: U) => {prop: T} & U; + assoc(prop: string, val: T): (obj: U) => {prop: T} & U; + + + /** + * Makes a shallow clone of an object, setting or overriding the nodes required to create the given path, and + * placing the specific value at the tail end of that path. + */ + assocPath(path: string[], val: T, obj: U): U; + assocPath(path: string[]): (val: T, obj: U) => U; + assocPath(path: string[], val: T): (obj: U) => U; + + /** + * Wraps a function of any arity (including nullary) in a function that accepts exactly 2 + * parameters. Any extraneous parameters will not be passed to the supplied function. + */ + binary(fn: (...args: any[]) => any): Function; + + /** + * Creates a function that is bound to a context. Note: R.bind does not provide the additional argument-binding + * capabilities of Function.prototype.bind. + */ + bind(thisObj: T, fn: (...args: any[]) => any): (...args: any[]) => any; + + + /** + * A function wrapping calls to the two functions in an && operation, returning the result of the first function + * if it is false-y and the result of the second function otherwise. Note that this is short-circuited, meaning + * that the second function will not be invoked if the first returns a false-y value. + */ + both(pred1: Pred, pred2: Pred): Pred; + both(pred1: Pred): (pred2: Pred) => Pred; + + /** + * Returns the result of calling its first argument with the remaining arguments. This is occasionally useful + * as a converging function for R.converge: the left branch can produce a function while the right branch + * produces a value to be passed to that function as an argument. + */ + call(fn: (...args: any[])=> (...args: any[]) => any, ...args: any[]): any; + + /** + * `chain` maps a function over a list and concatenates the results. + * This implementation is compatible with the Fantasy-land Chain spec + */ + chain(fn: (n: T) => U[], list: T[]): U[]; + chain(fn: (n: T) => U[]): (list: T[]) => U[]; + + /** + * Restricts a number to be within a range. + * Also works for other ordered types such as Strings and Date + */ + clamp(min: T, max: T, value: T): T; + clamp(min: T, max: T): (value: T) => T; + clamp(min: T): (max: T, value: T) => T; + clamp(min: T): (max: T) => (value: T) => T; + + /** + * Creates a deep copy of the value which may contain (nested) Arrays and Objects, Numbers, Strings, Booleans and Dates. + */ + clone(value: T): T; + clone(value: T[]): T[]; + + /** + * Makes a comparator function out of a function that reports whether the first element is less than the second. + */ + // comparator(pred: (a: any, b: any) => boolean): (x: number, y: number) => number; + comparator(pred: (a: T, b: T) => boolean): (x: T, y: T) => number; + + /** + * Takes a function f and returns a function g such that: + * - applying g to zero or more arguments will give true if applying the same arguments to f gives + * a logical false value; and + * - applying g to zero or more arguments will give false if applying the same arguments to f gives + * a logical true value. + */ + complement(pred: (...args: any[]) => boolean): (...args: any[]) => boolean + + /** + * Performs right-to-left function composition. The rightmost function may have any arity; the remaining + * functions must be unary. + */ + compose(fn0: (x0: V0) => T1): (x0: V0) => T1; + compose(fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T1; + compose(fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T1; + + compose(fn1: (x: T1) => T2, fn0: (x0: V0) => T1): (x0: V0) => T2; + compose(fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T2; + compose(fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T2; + + compose(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T3; + compose(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T3; + compose(fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T3; + + compose(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T4; + compose(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T4; + compose(fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T4; + + compose(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T5; + compose(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T5; + compose(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T5; + + compose(fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T6; + compose(fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T6; + compose(fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T6; + + /** + * TODO composeK + */ + + /** + * TODO composeP + */ + + + /** + * Returns a new list consisting of the elements of the first list followed by the elements + * of the second. + */ + concat(list1: T[], list2: T[]): T[]; + concat(list1: T[]): (list2: T[]) => T[]; + concat(list1: string, list2: string): string; + concat(list1: string): (list2: string) => string; + + /** + * Returns a function, fn, which encapsulates if/else-if/else logic. R.cond takes a list of [predicate, transform] pairs. + * All of the arguments to fn are applied to each of the predicates in turn until one returns a "truthy" value, at which + * point fn returns the result of applying its arguments to the corresponding transformer. If none of the predicates + * matches, fn returns undefined. + */ + cond(fns: [Pred, Function][]): Function; + + + /** + * Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. + */ + construct(fn: Function): Function; + + + /** + * Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. + * The arity of the function returned is specified to allow using variadic constructor functions. + */ + constructN(n: number, fn: Function): Function; + + + /** + * Returns `true` if the specified item is somewhere in the list, `false` otherwise. + * Equivalent to `indexOf(a)(list) > -1`. Uses strict (`===`) equality checking. + */ + contains(a: string, list: string): boolean; + contains(a: T, list: T[]): boolean; + contains(a: string): (list: string) => boolean; + contains(a: T): (list: T[]) => boolean; + + /** + * Accepts a converging function and a list of branching functions and returns a new + * function. When invoked, this new function is applied to some arguments, each branching + * function is applied to those same arguments. The results of each branching function + * are passed as arguments to the converging function to produce the return value. + */ + converge(after: Function, fns: Function[]): Function; + + /** + * Counts the elements of a list according to how many match each value + * of a key generated by the supplied function. Returns an object + * mapping the keys produced by `fn` to the number of occurrences in + * the list. Note that all keys are coerced to strings because of how + * JavaScript objects work. + */ + countBy(fn: (a: any) => string|number, list: any[]): any; + countBy(fn: (a: any) => string|number): (list: any[]) => any; + + /** + * Returns a curried equivalent of the provided function. The curried function has two unusual capabilities. + * First, its arguments needn't be provided one at a time. + */ + curry(fn: (a: T1, b: T2) => TResult): CurriedFunction2 + curry(fn: (a: T1, b: T2, c: T3) => TResult): CurriedFunction3 + curry(fn: (a: T1, b: T2, c: T3, d: T4) => TResult): CurriedFunction4 + curry(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => TResult): CurriedFunction5 + curry(fn: (a: T1, b: T2, c: T3, d: T4, e: T5, f: T6) => TResult): CurriedFunction6 + curry(fn: Function): Function + + + /** + * Returns a curried equivalent of the provided function, with the specified arity. The curried function has + * two unusual capabilities. First, its arguments needn't be provided one at a time. + */ + curryN(length: number, fn: (...args: any[]) => any): Function; + + + /** + * Decrements its argument. + */ + dec(n: number): number; + + /** + * Returns the second argument if it is not null or undefined. If it is null or undefined, the + * first (default) argument is returned. + */ + defaultTo(a: T, b: U): T|U + defaultTo(a: T): (b: U) => T|U + + /** + * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. + */ + difference(list1: T[], list2: T[]): T[]; + difference(list1: T[]): (list2: T[]) => T[]; + + /** + * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. + * Duplication is determined according to the value returned by applying the supplied predicate to two list + * elements. + */ + differenceWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + + /* + * Returns a new object that does not contain a prop property. + */ + // It seems impossible to infer the return type, so this may to be specified explicitely + dissoc(prop: string, obj: any): T; + dissoc(prop: string): (obj: any) => U; + + /** + * Makes a shallow clone of an object, omitting the property at the given path. + */ + dissocPath(path: string[], obj: any): T; + dissocPath(path: string[]): (obj: any) => T; + + /** + * Divides two numbers. Equivalent to a / b. + */ + divide(a: number, b: number): number; + divide(a: number): (b: number) => number; + + /** + * Returns a new list containing all but the first n elements of the given list. + */ + drop(n: number, xs: T[]): T[]; + drop(n: number, xs: string): string; + drop(n: number): { + (xs: string): string; + (xs: T[]): T[]; + } + + /** + * Returns a list containing all but the last n elements of the given list. + */ + dropLast(n: number, xs: T[]): T[]; + dropLast(n: number, xs: string): string; + dropLast(n: number): { + (xs: T[]): T[]; + (xs: string): string; + } + + /** + * Returns a new list containing all but last then elements of a given list, passing each value from the + * right to the supplied predicate function, skipping elements while the predicate function returns true. + */ + dropLastWhile(fn: (a: T) => boolean, list: T[]): T[]; + dropLastWhile(fn: (a: T) => boolean): (list: T[]) => T[]; + + /** + * Returns a new list containing the last n elements of a given list, passing each value to the supplied + * predicate function, skipping elements while the predicate function returns true. + */ + dropWhile(fn: (a: T) => boolean, list: T[]): T[]; + dropWhile(fn: (a: T) => boolean): (list: T[]) => T[]; + + /** + * A function wrapping calls to the two functions in an || operation, returning the result of the first + * function if it is truth-y and the result of the second function otherwise. Note that this is + * short-circuited, meaning that the second function will not be invoked if the first returns a truth-y value. + */ + either(pred1: Pred, pred2: Pred): Pred; + either(pred1: Pred): (pred2: Pred) => Pred; + + /** + * Returns the empty value of its argument's type. Ramda defines the empty value of Array ([]), Object ({}), + * String (''), and Arguments. Other types are supported if they define .empty and/or .prototype.empty. + * Dispatches to the empty method of the first argument, if present. + */ + empty(x: T): T; + + /** + * Takes a function and two values in its domain and returns true if the values map to the same value in the + * codomain; false otherwise. + */ + eqBy(fn: (a: T) => T, a: T, b: T): boolean; + eqBy(fn: (a: T) => T, a: T): (b: T) => boolean; + eqBy(fn: (a: T) => T): (a: T, b: T) => boolean; + eqBy(fn: (a: T) => T): (a: T) => (b: T) => boolean; + + /** + * Reports whether two functions have the same value for the specified property. + */ + eqProps(prop: string, obj1: T, obj2: U): boolean; + eqProps(prop: string): (obj1: T, obj2: U) => boolean; + eqProps(prop: string, obj1: T): (obj2: U) => boolean; + + /** + * Returns true if its arguments are equivalent, false otherwise. Dispatches to an equals method if present. + * Handles cyclical data structures. + */ + equals(a: T, b: T): boolean; + equals(a: T): (b: T) => boolean; + + /** + * Creates a new object by evolving a shallow copy of object, according to the transformation functions. + */ + evolve(transformations: Nested, obj: V): Nested; + evolve(transformations: Nested): (obj: V) => Nested; + /* + * A function that always returns false. Any passed in parameters are ignored. + */ + F(): boolean; + + /** + * Returns a new list containing only those items that match a given predicate function. The predicate function is passed one argument: (value). + */ + filter(fn: (value: T) => boolean): (list: T[]) => T[]; + filter(fn: (value: T) => boolean, list: T[]): T[]; + + /** + * Returns the first element of the list which matches the predicate, or `undefined` if no + * element matches. + */ + find(fn: (a: T) => boolean, list: T[]): T; + find(fn: (a: T) => boolean): (list: T[]) => T; + + + /** + * Returns the index of the first element of the list which matches the predicate, or `-1` + * if no element matches. + */ + findIndex(fn: (a: T) => boolean, list: T[]): number; + findIndex(fn: (a: T) => boolean): (list: T[]) => number; + + /** + * Returns the last element of the list which matches the predicate, or `undefined` if no + * element matches. + */ + findLast(fn: (a: T) => boolean, list: T[]): T; + findLast(fn: (a: T) => boolean): (list: T[]) => T; + + /** + * Returns the index of the last element of the list which matches the predicate, or + * `-1` if no element matches. + */ + findLastIndex(fn: (a: T) => boolean, list: T[]): number; + findLastIndex(fn: (a: T) => boolean): (list: T[]) => number; + + /** + * Returns a new list by pulling every item out of it (and all its sub-arrays) and putting + * them in a new array, depth-first. + */ + flatten(x: T[][]): T[]; + flatten(x: T[]): T[]; + + /** + * Returns a new function much like the supplied one, except that the first two arguments' + * order is reversed. + */ + flip(fn: (arg0: T, arg1: U) => TResult): (arg1: U, arg0?: T) => TResult; + flip(fn: (arg0: T, arg1: U, ...args: any[]) => TResult): (arg1: U, arg0?: T, ...args: any[]) => TResult; + + + /** + * Iterate over an input list, calling a provided function fn for each element in the list. + */ + forEach(fn: (x: T) => void, list: T[]): T[]; + forEach(fn: (x: T) => void): (list: T[]) => T[]; + + /** + * Creates a new object out of a list key-value pairs. + */ + fromPairs(pairs: KeyValuePair[]): {[index: string]: V}; + fromPairs(pairs: KeyValuePair[]): {[index: number]: V}; + + /** + * Splits a list into sublists stored in an object, based on the result of + * calling a String-returning function + * on each element, and grouping the results according to values returned. + */ + groupBy(fn: (a: T) => string, list: T[]): {[index: string]: T[]} + groupBy(fn: (a: T) => string): (list: T[]) => {[index: string]: T[]} + + /** + * Takes a list and returns a list of lists where each sublist's elements are all "equal" according to the provided equality function + */ + groupWith(fn: (x: T, y: T) => boolean, list: T[]): T[][] + groupWith(fn: (x: T, y: T) => boolean, list: string): string[] + + /** + * Returns true if the first parameter is greater than the second. + */ + gt(a: number, b: number): boolean; + gt(a: number): (b: number) => boolean; + + /** + * Returns true if the first parameter is greater than or equal to the second. + */ + gte(a: number, b: number): boolean; + gte(a: number): (b: number) => boolean; + + /** + * Returns whether or not an object has an own property with the specified name. + */ + has(s: string, obj: T): boolean; + has(s: string): (obj: T) => boolean; + + /** + * Returns whether or not an object or its prototype chain has a property with the specified name + */ + hasIn(s: string, obj: T): boolean; + hasIn(s: string): (obj: T) => boolean; + + /** + * Returns the first element in a list. + * In some libraries this function is named `first`. + */ + head(list: T[]): T; + head(list: string): string; + + /** + * Returns true if its arguments are identical, false otherwise. Values are identical if they reference the + * same memory. NaN is identical to NaN; 0 and -0 are not identical. + */ + identical(a: T, b: T): boolean; + identical(a: T): (b: T) => boolean; + + + /** + * A function that does nothing but return the parameter supplied to it. Good as a default + * or placeholder function. + */ + identity(a: T): T; + + /** + * Creates a function that will process either the onTrue or the onFalse function depending upon the result + * of the condition predicate. + */ + ifElse(fn: Pred, onTrue: Arity1Fn, onFalse: Arity1Fn): Arity1Fn; + + + /** + * Increments its argument. + */ + inc(n: number): number; + + /** + * Given a function that generates a key, turns a list of objects into an object indexing the objects + * by the given key. + */ + indexBy(fn: (a: T) => string, list: T[]): U; + indexBy(fn: (a: T) => string): (list: T[]) => U; + + /** + * Returns the position of the first occurrence of an item in an array + * (by strict equality), + * or -1 if the item is not included in the array. + */ + indexOf(target: T, list: T[]): number; + indexOf(target: T): (list: T[]) => number; + + /** + * Returns all but the last element of a list. + */ + init(list: T[]): T[]; + + /** + * Inserts the supplied element into the list, at index index. Note that + * this is not destructive: it returns a copy of the list with the changes. + */ + insert(index: number, elt: T, list: T[]): T[]; + insert(index: number, elt: T): (list: T[]) => T[]; + insert(index: number): (elt: T, list: T[]) => T[]; + + /** + * Inserts the sub-list into the list, at index `index`. _Note that this + * is not destructive_: it returns a copy of the list with the changes. + */ + insertAll(index: number, elts: T[], list: T[]): T[]; + insertAll(index: number, elts: T[]): (list: T[]) => T[]; + insertAll(index: number): (elts: T[], list: T[]) => T[]; + + + /** + * Combines two lists into a set (i.e. no duplicates) composed of those elements common to both lists. + */ + intersection(list1: T[], list2: T[]): T[]; + + + /** + * Combines two lists into a set (i.e. no duplicates) composed of those + * elements common to both lists. Duplication is determined according + * to the value returned by applying the supplied predicate to two list + * elements. + */ + intersectionWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + + /** + * Creates a new list with the separator interposed between elements. + */ + intersperse(separator: T, list: T[]): T[]; + intersperse(separator: T): (list: T[]) => T[]; + + /** + * Transforms the items of the list with the transducer and appends the transformed items to the accumulator + * using an appropriate iterator function based on the accumulator type. + */ + into(acc: any, xf: Function, list: T[]): T[]; + into(acc: any, xf: Function): (list: T[]) => T[]; + into(acc: any): (xf: Function, list: T[]) => T[]; + + /** + * Same as R.invertObj, however this accounts for objects with duplicate values by putting the values into an array. + */ + invert(obj: T): {[index:string]: string[]}; + + /** + * Returns a new object with the keys of the given object as values, and the values of the given object as keys. + */ + invertObj(obj: any): {[index:string]: string}; + invertObj(obj: {[index: number]: string}): {[index:string]: string}; + + + /** + * Turns a named method of an object (or object prototype) into a function that can be + * called directly. Passing the optional `len` parameter restricts the returned function to + * the initial `len` parameters of the method. + * + * The returned function is curried and accepts `len + 1` parameters (or `method.length + 1` + * when `len` is not specified), and the final parameter is the target object. + */ + invoker(name: string, obj: any, len?: number): Function; + invoker(name: string): (obj: any, len?: number) => Function; + + /** + * See if an object (`val`) is an instance of the supplied constructor. + * This function will check up the inheritance chain, if any. + */ + is(ctor: any, val: any): boolean; + is(ctor: any): (val: any) => boolean; + + /** + * Tests whether or not an object is similar to an array. + */ + isArrayLike(val: any): boolean; + + /** + * Reports whether the list has zero elements. + */ + isEmpty(value: any): boolean; + + + /** + * Returns true if the input value is NaN. + */ + isNaN(x: any): boolean; + + /** + * Checks if the input value is null or undefined. + */ + isNil(value: any): boolean; + + /** + * Returns a string made by inserting the `separator` between each + * element and concatenating all the elements into a single string. + */ + join(x: string, xs: any[]): string; + join(x: string): (xs: any[]) => string; + + /** + * Applies a list of functions to a list of values. + */ + juxt(fns: {(...args: T[]): U}[]): (...args: T[]) => U[]; + + + /** + * Returns a list containing the names of all the enumerable own + * properties of the supplied object. + */ + keys(x: T): string[]; + + /** + * Returns a list containing the names of all the + * properties of the supplied object, including prototype properties. + */ + keysIn(obj: T): string[]; + + /** + * Returns the last element from a list. + */ + last(list: T[]): T; + last(list: string): string; + + /** + * Returns the position of the last occurrence of an item (by strict equality) in + * an array, or -1 if the item is not included in the array. + */ + lastIndexOf(target: T, list: T[]): number; + + /** + * Returns the number of elements in the array by returning list.length. + */ + length(list: any[]): number; + + /** + * Returns a lens for the given getter and setter functions. The getter + * "gets" the value of the focus; the setter "sets" the value of the focus. + * The setter should not mutate the data structure. + */ + lens(getter: (s: T) => U, setter: (a: U, s: T) => V): Lens; + + /** + * Creates a lens that will focus on index n of the source array. + */ + lensIndex(n: number): Lens; + + /** + * Returns a lens whose focus is the specified path. + * See also view, set, over. + */ + lensPath(path: string[]): Lens; + + /** + * lensProp creates a lens that will focus on property k of the source object. + */ + lensProp(str: string): { + (obj: T): U; + set(val: T, obj: U): V; + /*map(fn: Function, obj: T): T*/ + } + + /** + * "lifts" a function of arity > 1 so that it may "map over" a list, Function or other object that satisfies + * the FantasyLand Apply spec. + */ + lift(fn: Function, ...args: any[]): any; + + /** + * "lifts" a function to be the specified arity, so that it may "map over" that many lists, Functions or other + * objects that satisfy the FantasyLand Apply spec. + */ + liftN(n: number, fn: Function, ...args: any[]): any; + + + /** + * Returns true if the first parameter is less than the second. + */ + lt(a: number, b: number): boolean; + lt(a: number): (b: number) => boolean; + + /** + * Returns true if the first parameter is less than or equal to the second. + */ + lte(a: number, b: number): boolean; + lte(a: number): (b: number) => boolean; + + /** + * Returns a new list, constructed by applying the supplied function to every element of the supplied list. + */ + map(fn: (x: T) => U, list: T[]): U[]; + map(fn: (x: T) => U, obj: Functor): Functor; // used in functors + map(fn: (x: T) => U): (list: T[]) => U[]; + + /** + * The mapAccum function behaves like a combination of map and reduce. + */ + mapAccum(fn: (acc: U, value: T) => [U, TResult], acc: U, list: T[]): [U, TResult[]]; + mapAccum(fn: (acc: U, value: T) => [U, TResult]): (acc: U, list: T[]) => [U, TResult[]]; + mapAccum(fn: (acc: U, value: T) => [U, TResult], acc: U): (list: T[]) => [U, TResult[]]; + + /** + * The mapAccumRight function behaves like a combination of map and reduce. + */ + mapAccumRight(fn: (acc: U, value: T) => [U, TResult], acc: U, list: T[]): [U, TResult[]]; + mapAccumRight(fn: (acc: U, value: T) => [U, TResult]): (acc: U, list: T[]) => [U, TResult[]]; + mapAccumRight(fn: (acc: U, value: T) => [U, TResult], acc: U): (list: T[]) => [U, TResult[]]; + + + /** + * Like mapObj, but but passes additional arguments to the predicate function. + */ + mapObjIndexed(fn: (value: T, key: string, obj?: any) => TResult, obj: any): {[index:string]: TResult}; + mapObjIndexed(fn: (value: T, key: string, obj?: any) => TResult): (obj: any) => {[index:string]: TResult}; + + /** + * Tests a regular expression agains a String + */ + match(regexp: RegExp, str: string): any[]; + match(regexp: RegExp): (str: string) => any[]; + + + /** + * mathMod behaves like the modulo operator should mathematically, unlike the `%` + * operator (and by extension, R.modulo). So while "-17 % 5" is -2, + * mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN + * when the modulus is zero or negative. + */ + mathMod(a: number, b: number): number; + mathMod(a: number): (b: number) => number; + + + /** + * Returns the larger of its two arguments. + */ + max(a: Ord, b: Ord): Ord; + max(a: Ord): (b: Ord) => Ord; + + /** + * Takes a function and two values, and returns whichever value produces + * the larger result when passed to the provided function. + */ + maxBy(keyFn: (a: T) => Ord, a: T, b: T): T; + maxBy(keyFn: (a: T) => Ord, a: T): (b: T) => T; + maxBy(keyFn: (a: T) => Ord): CurriedFunction2 + + /** + * Returns the mean of the given list of numbers. + */ + mean(list: number[]): number; + + /** + * Returns the median of the given list of numbers. + */ + median(list: number[]): number; + + /** + * Creates a new function that, when invoked, caches the result of calling fn for a given argument set and + * returns the result. Subsequent calls to the memoized fn with the same argument set will not result in an + * additional call to fn; instead, the cached result for that set of arguments will be returned. + */ + memoize(fn: Function): Function; + + /** + * Create a new object with the own properties of a + * merged with the own properties of object b. + * This function will *not* mutate passed-in objects. + */ + merge(a: T1, b: T2): T1 & T2; + merge(a: T1): (b: T2) => T1 & T2; + + + /** + * Merges a list of objects together into one object. + */ + mergeAll(list: any[]): T; + + /** + * Creates a new object with the own properties of the two provided objects. If a key exists in both objects, + * the provided function is applied to the values associated with the key in each object, with the result being used as + * the value associated with the key in the returned object. The key will be excluded from the returned object if the + * resulting value is undefined. + */ + mergeWith(fn: (x: any, z: any) => any, a: U, b: V): U & V; + mergeWith(fn: (x: any, z: any) => any, a: U): (b: V) => U & V; + mergeWith(fn: (x: any, z: any) => any): (a: U, b: V) => U & V; + + /** + * Creates a new object with the own properties of the two provided objects. If a key exists in both objects, + * the provided function is applied to the key and the values associated with the key in each object, with the + * result being used as the value associated with the key in the returned object. The key will be excluded from + * the returned object if the resulting value is undefined. + */ + mergeWithKey(fn: (str: string, x: any, z: any) => any, a: U, b: V): U & V; + mergeWithKey(fn: (str: string, x: any, z: any) => any, a: U): (b: V) => U & V; + mergeWithKey(fn: (str: string, x: any, z: any) => any): (a: U, b: V) => U & V; + + /** + * Returns the smaller of its two arguments. + */ + min(a: Ord, b: Ord): Ord; + min(a: Ord): (b: Ord) => Ord; + + /** + * Takes a function and two values, and returns whichever value produces + * the smaller result when passed to the provided function. + */ + minBy(keyFn: (a: T) => Ord, a: T, b: T): T; + minBy(keyFn: (a: T) => Ord, a: T): (b: T) => T; + minBy(keyFn: (a: T) => Ord): CurriedFunction2 + + /** + * Divides the second parameter by the first and returns the remainder. + * The flipped version (`moduloBy`) may be more useful curried. + * Note that this functions preserves the JavaScript-style behavior for + * modulo. For mathematical modulo see `mathMod` + */ + modulo(a: number, b: number): number; + modulo(a: number): (b: number) => number; + + /** + * Multiplies two numbers. Equivalent to a * b but curried. + */ + multiply(a: number, b: number): number; + multiply(a: number): (b: number) => number; + + + /** + * Wraps a function of any arity (including nullary) in a function that accepts exactly n parameters. + * Any extraneous parameters will not be passed to the supplied function. + */ + nAry(n: number, fn: (...arg: any[]) => any): Function; + + /** + * Negates its argument. + */ + negate(n: number): number; + + + /** + * Returns true if no elements of the list match the predicate, false otherwise. + */ + none(fn: (a: T) => boolean, list: T[]): boolean; + none(fn: (a: T) => boolean): (list: T[]) => boolean; + + + /** + * A function wrapping a call to the given function in a `!` operation. It will return `true` when the + * underlying function would return a false-y value, and `false` when it would return a truth-y one. + */ + not(value: any): boolean; + + /** + * Returns the nth element in a list. + */ + nth(n: number, list: T[]): T; + nth(n: number): (list: T[]) => T; + + /** + * Returns a function which returns its nth argument. + */ + nthArg(n: number): (...a: any[]) => any; + + /** + * Creates an object containing a single key:value pair. + */ + objOf(key: string, value: T): {string: T}; + objOf(key: string): (value: T) => {string: T}; + + /** + * Returns a singleton array containing the value provided. + */ + of(x: T): T[]; + //of(x: T[]): T[][]; unnecessary typing and introduced error in unless example + + /** + * Returns a partial copy of an object omitting the keys specified. + */ + omit(names: string[], obj: T): T; + omit(names: string[]): (obj: T) => T; + + /** + * Accepts a function fn and returns a function that guards invocation of fn such that fn can only ever be + * called once, no matter how many times the returned function is invoked. The first value calculated is + * returned in subsequent invocations. + */ + once(fn: Function): Function; + + /** + * A function that returns the first truthy of two arguments otherwise the last argument. Note that this is + * NOT short-circuited, meaning that if expressions are passed they are both evaluated. + * Dispatches to the or method of the first argument if applicable. + */ + or(a: T, b: U): T|U; + or(a: T): (b: U) => T|U; + or(fn1: T, val2: U): T|U; + or(fn1: T): (val2: U) => T|U; + + + /** + * Returns the result of "setting" the portion of the given data structure + * focused by the given lens to the given value. + */ + over(lens: Lens, fn: Arity1Fn, value: T): T; + over(lens: Lens, fn: Arity1Fn, value: T[]): T[]; + over(lens: Lens, fn: Arity1Fn): (value: T) => T; + over(lens: Lens, fn: Arity1Fn): (value: T[]) => T[]; + over(lens: Lens): (fn: Arity1Fn, value: T) => T; + over(lens: Lens): (fn: Arity1Fn, value: T[]) => T[]; + + + /** + * Takes two arguments, fst and snd, and returns [fst, snd]. + */ + pair(fst: F, snd: S): [F, S]; + + /** + * Accepts as its arguments a function and any number of values and returns a function that, + * when invoked, calls the original function with all of the values prepended to the + * original function's arguments list. In some libraries this function is named `applyLeft`. + */ + partial(fn: Function, ...args: any[]): Function; + + /** + * Accepts as its arguments a function and any number of values and returns a function that, + * when invoked, calls the original function with all of the values appended to the original + * function's arguments list. + */ + partialRight(fn: Function, ...args: any[]): Function; + + /** + * Takes a predicate and a list and returns the pair of lists of elements + * which do and do not satisfy the predicate, respectively. + */ + partition(fn: (a: string) => boolean, list: string[]): string[][]; + partition(fn: (a: T) => boolean, list: T[]): T[][]; + partition(fn: (a: T) => boolean): (list: T[]) => T[][]; + partition(fn: (a: string) => boolean): (list: string[]) => string[][]; + + /** + * Retrieve the value at a given path. + */ + path(path: string[], obj: any): T; + path(path: string[]): (obj: any) => T; + + /** + * Determines whether a nested path on an object has a specific value, + * in `R.equals` terms. Most likely used to filter a list. + */ + pathEq(path: string[], val: any, obj: any): boolean; + pathEq(path: string[], val: any): (obj: any) => boolean; + pathEq(path: string[]): (val: any, obj: any) => boolean; + pathEq(path: string[]): (val: any) => (obj: any) => boolean; + + /** + * If the given, non-null object has a value at the given path, returns the value at that path. + * Otherwise returns the provided default value. + */ + pathOr(d: T, p: string[], obj: any): T|any; + pathOr(d: T, p: string[]): (obj: any) => T|any; + pathOr(d: T): (p: string[], obj: any) => T|any; + + + /** + * Returns a partial copy of an object containing only the keys specified. If the key does not exist, the + * property is ignored. + */ + pick(names: string[], obj: T): U; + pick(names: string[]): (obj: T) => U; + + + /** + * Similar to `pick` except that this one includes a `key: undefined` pair for properties that don't exist. + */ + pickAll(names: string[], obj: T): U; + pickAll(names: string[]): (obj: T) => U; + + + /** + * Returns a partial copy of an object containing only the keys that satisfy the supplied predicate. + */ + pickBy(pred: ObjPred, obj: T): U; + pickBy(pred: ObjPred): (obj: T) => U; + + + /** + * Creates a new function that runs each of the functions supplied as parameters in turn, + * passing the return value of each function invocation to the next function invocation, + * beginning with whatever arguments were passed to the initial invocation. + */ + pipe(fn0: (x0: V0) => T1): (x0: V0) => T1; + pipe(fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T1; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T1; + + pipe(fn0: (x0: V0) => T1, fn1: (x: T1) => T2): (x0: V0) => T2; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2): (x0: V0, x1: V1) => T2; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2): (x0: V0, x1: V1, x2: V2) => T2; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x: V0) => T3; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x0: V0, x1: V1) => T3; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3): (x0: V0, x1: V1, x2: V2) => T3; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x: V0) => T4; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x0: V0, x1: V1) => T4; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4): (x0: V0, x1: V1, x2: V2) => T4; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x: V0) => T5; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x0: V0, x1: V1) => T5; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5): (x0: V0, x1: V1, x2: V2) => T5; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x: V0) => T6; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x0: V0, x1: V1) => T6; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x0: V0, x1: V1, x2: V2) => T6; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn: (x: T6) => T7): (x: V0) => T7; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7): (x0: V0, x1: V1) => T7; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7): (x0: V0, x1: V1, x2: V2) => T7; + + pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T6) => T7, fn: (x: T7) => T8): (x: V0) => T8; + pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T5) => T6, fn7: (x: T7) => T8): (x0: V0, x1: V1) => T8; + pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6, fn6: (x: T5) => T6, fn7: (x: T7) => T8): (x0: V0, x1: V1, x2: V2) => T8; + + + /** + * Returns a new list by plucking the same named property off all objects in the list supplied. + */ + pluck(p: string|number, list: any[]): T[]; + pluck(p: string|number): (list: any[]) => T[]; + + /** + * Returns a new list with the given element at the front, followed by the contents of the + * list. + */ + prepend(el: T, list: T[]): T[]; + prepend(el: T): (list: T[]) => T[]; + + /** + * Multiplies together all the elements of a list. + */ + product(list: number[]): number; + + + /** + * Reasonable analog to SQL `select` statement. + */ + project(props: string[], objs: T[]): U[]; + + /** + * Returns a function that when supplied an object returns the indicated property of that object, if it exists. + * Note: TS1.9 # replace any by dictionary + */ + prop(p: string, obj: any): T; + prop(p: string): (obj: any) => T; + + /** + * Determines whether the given property of an object has a specific + * value according to strict equality (`===`). Most likely used to + * filter a list. + */ + // propEq(name: string, val: T, obj: {[index:string]: T}): boolean; + // propEq(name: string, val: T, obj: {[index:number]: T}): boolean; + propEq(name: string, val: T, obj: any): boolean; + // propEq(name: number, val: T, obj: any): boolean; + propEq(name: string, val: T): (obj: any) => boolean; + // propEq(name: number, val: T): (obj: any) => boolean; + propEq(name: string): (val: T, obj: any) => boolean; + // propEq(name: number): (val: T, obj: any) => boolean; + + /** + * Returns true if the specified object property is of the given type; false otherwise. + */ + propIs(type: any, name: string, obj: any): boolean; + propIs(type: any, name: string): (obj: any) => boolean; + propIs(type: any): { + (name: string, obj: any): boolean; + (name: string): (obj: any) => boolean; + } + + /** + * If the given, non-null object has an own property with the specified name, returns the value of that property. + * Otherwise returns the provided default value. + */ + propOr(val: T, p: string, obj: U): V; + propOr(val: T, p: string): (obj: U) => V; + propOr(val: T): (p: string, obj: U) => V; + + /** + * Returns the value at the specified property. + * The only difference from `prop` is the parameter order. + * Note: TS1.9 # replace any by dictionary + */ + props(ps: string[], obj: any): T[]; + props(ps: string[]): (obj: any) => T[]; + + /** + * Returns true if the specified object property satisfies the given predicate; false otherwise. + */ + propSatisfies(pred: (val: T) => boolean, name: string, obj: U): boolean; + propSatisfies(pred: (val: T) => boolean, name: string): (obj: U) => boolean; + propSatisfies(pred: (val: T) => boolean): CurriedFunction2; + + /** + * Returns a list of numbers from `from` (inclusive) to `to` + * (exclusive). In mathematical terms, `range(a, b)` is equivalent to + * the half-open interval `[a, b)`. + */ + range(from: number, to: number): number[]; + range(from: number): (to: number) => number[]; + + /** + * Returns a single item by iterating through the list, successively calling the iterator + * function and passing it an accumulator value and the current value from the array, and + * then passing the result to the next call. + */ + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult, list: T[]): TResult; + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced): (acc: TResult, list: T[]) => TResult; + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult): (list: T[]) => TResult; + + /** + * Groups the elements of the list according to the result of calling the String-returning function keyFn on each + * element and reduces the elements of each group to a single value via the reducer function valueFn. + */ + reduceBy(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult, keyFn: (elem: T) => string, list: T[]): {[index: string]: TResult}; + reduceBy(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult, keyFn: (elem: T) => string): (list: T[]) => {[index: string]: TResult}; + reduceBy(valueFn: (acc: TResult, elem: T) => TResult, acc: TResult): CurriedFunction2<(elem: T) => string, T[], {[index: string]: TResult}>; + reduceBy(valueFn: (acc: TResult, elem: T) => TResult): CurriedFunction3 string, T[], {[index: string]: TResult}>; + + /** + * Returns a value wrapped to indicate that it is the final value of the reduce and + * transduce functions. The returned value should be considered a black box: the internal + * structure is not guaranteed to be stable. + */ + reduced(elem: T): Reduced; + + /** + * Returns a single item by iterating through the list, successively calling the iterator + * function and passing it an accumulator value and the current value from the array, and + * then passing the result to the next call. + */ + reduceRight(fn: (acc: TResult, elem: T) => TResult, acc: TResult, list: T[]): TResult; + reduceRight(fn: (acc: TResult, elem: T) => TResult): (acc: TResult, list: T[]) => TResult; + reduceRight(fn: (acc: TResult, elem: T) => TResult, acc: TResult): (list: T[]) => TResult; + + /** + * Similar to `filter`, except that it keeps only values for which the given predicate + * function returns falsy. + */ + reject(fn: (value: T) => boolean, list: T[]): T[]; + reject(fn: (value: T) => boolean): (list: T[]) => T[]; + + /** + * Removes the sub-list of `list` starting at index `start` and containing `count` elements. + */ + remove(start: number, count: number, list: T[]): T[]; + remove(start: number): (count: number, list: T[]) => T[]; + remove(start: number, count: number): (list: T[]) => T[]; + + /** + * Returns a fixed list of size n containing a specified identical value. + */ + repeat(a: T, n: number): T[]; + repeat(a: T): (n: number) => T[]; + + + /** + * Replace a substring or regex match in a string with a replacement. + */ + replace(pattern: RegExp, replacement: string, str: string): string; + replace(pattern: RegExp, replacement: string): (str: string) => string; + replace(pattern: RegExp): (replacement: string) => (str: string) => string; + replace(pattern: String, replacement: string, str: string): string; + replace(pattern: String, replacement: string): (str: string) => string; + replace(pattern: String): (replacement: string) => (str: string) => string; + + + /** + * Returns a new list with the same elements as the original list, just in the reverse order. + */ + reverse(list: T[]): T[]; + + /** + * Scan is similar to reduce, but returns a list of successively reduced values from the left. + */ + scan(fn: (acc: TResult, elem: T) => any, acc: TResult, list: T[]): TResult[]; + scan(fn: (acc: TResult, elem: T) => any, acc: TResult): (list: T[]) => TResult[]; + scan(fn: (acc: TResult, elem: T) => any): (acc: TResult, list: T[]) => TResult[]; + + /** + * Returns the result of "setting" the portion of the given data structure focused by the given lens to the + * given value. + */ + set(lens: Lens, a: U, obj: T): T; + set(lens: Lens, a: U): (obj: T) => T; + set(lens: Lens): (a: U, obj: T) => T; + + /** + * Returns the elements from `xs` starting at `a` and ending at `b - 1`. + */ + slice(a: number, b: number, list: string): string; + slice(a: number, b: number, list: T[]): T[]; + slice(a: number, b: number): (list: string|T[]) => string|T[]; + slice(a: number): (b: number, list: string|T[]) => string|T[]; + + /** + * Returns a copy of the list, sorted according to the comparator function, which should accept two values at a + * time and return a negative number if the first value is smaller, a positive number if it's larger, and zero + * if they are equal. + */ + sort(fn: (a: T, b: T) => number, list: T[]): T[]; + sort(fn: (a: T, b: T) => number): (list: T[]) => T[]; + + + /** + * Sorts the list according to a key generated by the supplied function. + */ + sortBy(fn: (a: any) => string, list: T[]): T[]; + sortBy(fn: (a: any) => string): (list: T[]) => T[]; + + /** + * Splits a string into an array of strings based on the given + * separator. + */ + split(sep: string): (str: string) => string[]; + split(sep: RegExp): (str: string) => string[]; + split(sep: string, str: string): string[]; + split(sep: RegExp, str: string): string[]; + + /** + * Splits a given list or string at a given index. + */ + splitAt(index: number, list: T): T[]; + splitAt(index: number): (list: T) => T[]; + splitAt(index: number, list: T[]): T[][]; + splitAt(index: number): (list: T[]) => T[][]; + + /** + * Splits a collection into slices of the specified length. + */ + splitEvery(a: number, list: T[]): T[][]; + splitEvery(a: number): (list: T[]) => T[][]; + + + /** + * Takes a list and a predicate and returns a pair of lists with the following properties: + * - the result of concatenating the two output lists is equivalent to the input list; + * - none of the elements of the first output list satisfies the predicate; and + * - if the second output list is non-empty, its first element satisfies the predicate. + */ + splitWhen(pred: (val: T) => boolean, list: U[]): U[][]; + splitWhen(pred: (val: T) => boolean): (list: U[]) => U[][]; + + /** + * Subtracts two numbers. Equivalent to `a - b` but curried. + */ + subtract(a: number, b: number): number; + subtract(a: number): (b: number) => number; + + /** + * Adds together all the elements of a list. + */ + sum(list: number[]): number; + + /** + * Finds the set (i.e. no duplicates) of all elements contained in the first or second list, but not both. + */ + symmetricDifference(list1: T[], list2: T[]): T[]; + symmetricDifference(list: T[]): (list: T[]) => T[]; + + /** + * Finds the set (i.e. no duplicates) of all elements contained in the first or second list, but not both. + * Duplication is determined according to the value returned by applying the supplied predicate to two list elements. + */ + symmetricDifferenceWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + symmetricDifferenceWith(pred: (a: T, b: T) => boolean): CurriedFunction2; + + /** + * A function that always returns true. Any passed in parameters are ignored. + */ + T(): boolean; + + /** + * Returns all but the first element of a list. + */ + tail(list: T[]): T[]; + + /** + * Returns a new list containing the first `n` elements of the given list. If + * `n > * list.length`, returns a list of `list.length` elements. + */ + take(n: number, xs: T[]): T[]; + take(n: number, xs: string): string; + take(n: number): { + (xs: string): string; + (xs: T[]): T[]; + } + + + /** + * Returns a new list containing the last n elements of the given list. If n > list.length, + * returns a list of list.length elements. + */ + takeLast(n: number, xs: T[]): T[]; + takeLast(n: number, xs: string): string; + takeLast(n: number): { + (xs: T[]): T[]; + (xs: string): string; + } + + /** + * Returns a new list containing the last n elements of a given list, passing each value + * to the supplied predicate function, and terminating when the predicate function returns + * false. Excludes the element that caused the predicate function to fail. The predicate + * function is passed one argument: (value). + */ + takeLastWhile(pred: (a: T) => Boolean, list: T[]): T[]; + takeLastWhile(pred: (a: T) => Boolean): (list: T[]) => T[]; + + /** + * Returns a new list containing the first `n` elements of a given list, passing each value + * to the supplied predicate function, and terminating when the predicate function returns + * `false`. + */ + takeWhile(fn: (x: T) => boolean, list: T[]): T[]; + takeWhile(fn: (x: T) => boolean): (list: T[]) => T[]; + + /** + * The function to call with x. The return value of fn will be thrown away. + */ + tap(fn: (a: T) => any, value: T): T; + tap(fn: (a: T) => any): (value: T) => T; + + /** + * Determines whether a given string matches a given regular expression. + */ + test(regexp: RegExp, str: string): boolean; + test(regexp: RegExp): (str: string) => boolean; + + /** + * Calls an input function `n` times, returning an array containing the results of those + * function calls. + */ + times(fn: (i: number) => T, n: number): T[]; + times(fn: (i: number) => T): (n: number) => T[]; + + + /** + * The lower case version of a string. + */ + toLower(str: string): string; + + /** + * Converts an object into an array of key, value arrays. + * Only the object's own properties are used. + * Note that the order of the output array is not guaranteed to be + * consistent across different JS platforms. + */ + toPairs(obj: {[k: string]: S} | {[k: number]: S} | any): [F,S][]; + + /** + * Converts an object into an array of key, value arrays. + * The object's own properties and prototype properties are used. + * Note that the order of the output array is not guaranteed to be + * consistent across different JS platforms. + */ + toPairsIn(obj: {[k: string]: S} | {[k: number]: S} | any): [F,S][]; + + /** + * Returns the string representation of the given value. eval'ing the output should + * result in a value equivalent to the input value. Many of the built-in toString + * methods do not satisfy this requirement. + * + * If the given value is an [object Object] with a toString method other than + * Object.prototype.toString, this method is invoked with no arguments to produce the + * return value. This means user-defined constructor functions can provide a suitable + * toString method. + */ + toString(val: T): string; + + /** + * The upper case version of a string. + */ + toUpper(str: string): string; + + /** + * Initializes a transducer using supplied iterator function. Returns a single item by iterating through the + * list, successively calling the transformed iterator function and passing it an accumulator value and the + * current value from the array, and then passing the result to the next call. + */ + transduce(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[], acc: T[], list: T[]): U; + transduce(xf: (arg: T[]) => T[]): (fn: (acc: U[], val: U) => U[], acc: T[], list: T[]) => U; + transduce(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[]): (acc: T[], list: T[]) => U; + transduce(xf: (arg: T[]) => T[], fn: (acc: U[], val: U) => U[], acc: T[]): (list: T[]) => U; + + /** + * Transposes the rows and columns of a 2D list. When passed a list of n lists of length x, returns a list of x lists of length n. + */ + transpose(list: any[][]): any[][]; + + /** + * Removes (strips) whitespace from both ends of the string. + */ + trim(str: string): string; + + /** + * tryCatch takes two functions, a tryer and a catcher. The returned function evaluates the tryer; if it does + * not throw, it simply returns the result. If the tryer does throw, the returned function evaluates the catcher + * function and returns its result. Note that for effective composition with this function, both the tryer and + * catcher functions must return the same type of results. + */ + tryCatch(tryer: (...args: any[]) => T, catcher: (...args: any[]) => T, x: any): T; + + /** + * Gives a single-word string description of the (native) type of a value, returning such answers as 'Object', + * 'Number', 'Array', or 'Null'. Does not attempt to distinguish user Object types any further, reporting them + * all as 'Object'. + */ + type(val: any): string; + + /** + * Takes a function fn, which takes a single array argument, and returns a function which: + * - takes any number of positional arguments; + * - passes these arguments to fn as an array; and + * - returns the result. + * In other words, R.unapply derives a variadic function from a function which takes an array. + * R.unapply is the inverse of R.apply. + */ + unapply(fn: (args: any[]) => T): (...args: any[]) => T; + + /** + * Wraps a function of any arity (including nullary) in a function that accepts exactly 1 parameter. + * Any extraneous parameters will not be passed to the supplied function. + */ + unary(fn: (a: T, ...args: any[]) => any): (a: T) => any + + /** + * Returns a function of arity n from a (manually) curried function. + */ + uncurryN(len: number, fn: (a: any) => any): (...a: any[]) => T; + + /** + * Builds a list from a seed value. Accepts an iterator function, which returns either false + * to stop iteration or an array of length 2 containing the value to add to the resulting + * list and the seed to be used in the next call to the iterator function. + */ + unfold(fn: (seed: T) => TResult[]|boolean, seed: T): TResult[]; + unfold(fn: (seed: T) => TResult[]|boolean): (seed: T) => TResult[]; + + /** + * Combines two lists into a set (i.e. no duplicates) composed of the + * elements of each list. + */ + union(as: T[], bs: T[]): T[]; + union(as: T[]): (bs: T[]) => T[]; + + /** + * Combines two lists into a set (i.e. no duplicates) composed of the elements of each list. Duplication is + * determined according to the value returned by applying the supplied predicate to two list elements. + */ + unionWith(pred: (a: T, b: T) => boolean, list1: T[], list2: T[]): T[]; + unionWith(pred: (a: T, b: T) => boolean): CurriedFunction2 + + /** + * Returns a new list containing only one copy of each element in the original list. + */ + uniq(list: T[]): T[]; + + /** + * Returns a new list containing only one copy of each element in the original list, based upon the value returned by applying the supplied function to each list element. Prefers the first item if the supplied function produces the same value on two items. R.equals is used for comparison. + */ + uniqBy(fn: (a: T) => U, list: T[]): T[]; + uniqBy(fn: (a: T) => U): (list: T[]) => T[]; + + /** + * Returns a new list containing only one copy of each element in the original list, based upon the value + * returned by applying the supplied predicate to two list elements. + */ + uniqWith(pred: (x: T, y: T) => boolean, list: T[]): T[]; + uniqWith(pred: (x: T, y: T) => boolean): (list: T[]) => T[]; + + /** + * Tests the final argument by passing it to the given predicate function. If the predicate is not satisfied, + * the function will return the result of calling the whenFalseFn function with the same argument. If the + * predicate is satisfied, the argument is returned as is. + */ + unless(pred: (a: T) => boolean, whenFalseFn: (a: T) => U, obj: T): U; + unless(pred: (a: T) => boolean, whenFalseFn: (a: T) => U): (obj: T) => U; + + /** + * Returns a new list by pulling every item at the first level of nesting out, and putting + * them in a new array. + */ + unnest(x: T[][]): T[]; + unnest(x: T[]): T[]; + + /** + * Takes a predicate, a transformation function, and an initial value, and returns a value of the same type as + * the initial value. It does so by applying the transformation until the predicate is satisfied, at which point + * it returns the satisfactory value. + */ + until(pred: (val: T) => boolean, fn: (val: T) => U, init: U): U; + until(pred: (val: T) => boolean, fn: (val: T) => U): (init: U) => U; + + /** + * Returns a new copy of the array with the element at the provided index replaced with the given value. + */ + update(index: number, value: T, list: T[]): T[]; + update(index: number, value: T): (list: T[]) => T[]; + + /** + * Accepts a function fn and a list of transformer functions and returns a new curried function. + * When the new function is invoked, it calls the function fn with parameters consisting of the + * result of calling each supplied handler on successive arguments to the new function. + * + * If more arguments are passed to the returned function than transformer functions, those arguments + * are passed directly to fn as additional parameters. If you expect additional arguments that don't + * need to be transformed, although you can ignore them, it's best to pass an identity function so + * that the new function reports the correct arity. + */ + useWith(fn: Function, transformers: Function[]): Function; + + /** + * Returns a list of all the enumerable own properties of the supplied object. + * Note that the order of the output array is not guaranteed across + * different JS platforms. + */ + values(obj: {[index: string]: T}): T[]; + values(obj: any): T[]; + + /** + * Returns a list of all the properties, including prototype properties, of the supplied + * object. Note that the order of the output array is not guaranteed to be consistent across different JS platforms. + */ + valuesIn(obj: any): T[]; + + /** + * Returns a "view" of the given data structure, determined by the given lens. The lens's focus determines which + * portion of the data structure is visible. + */ + view(lens: Lens, obj: T): U; + + /** + * Tests the final argument by passing it to the given predicate function. If the predicate is satisfied, the function + * will return the result of calling the whenTrueFn function with the same argument. If the predicate is not satisfied, + * the argument is returned as is. + */ + when(pred: (a: T) => boolean, whenTrueFn: (a: T) => U, obj: T): U; + when(pred: (a: T) => boolean, whenTrueFn: (a: T) => U): (obj: T) => U; + + /** + * Takes a spec object and a test object and returns true if the test satisfies the spec. + * Any property on the spec that is not a function is interpreted as an equality + * relation. + * + * If the spec has a property mapped to a function, then `where` evaluates the function, passing in + * the test object's value for the property in question, as well as the whole test object. + * + * `where` is well suited to declarativley expressing constraints for other functions, e.g., + * `filter`, `find`, `pickWith`, etc. + */ + where(spec: T, testObj: U): boolean; + where(spec: T): (testObj: U) => boolean; + where(spec: ObjFunc2, testObj: U): boolean; + where(spec: ObjFunc2): (testObj: U) => boolean; + + /** + * Takes a spec object and a test object; returns true if the test satisfies the spec, + * false otherwise. An object satisfies the spec if, for each of the spec's own properties, + * accessing that property of the object gives the same value (in R.eq terms) as accessing + * that property of the spec. + */ + whereEq(spec: T, obj: U): boolean; + whereEq(spec: T): (obj: U) => boolean; + + /** + * Returns a new list without values in the first argument. R.equals is used to determine equality. + * Acts as a transducer if a transformer is given in list position. + */ + without(list1: T[], list2: T[]): T[]; + without(list1: T[]): (list2: T[]) => T[]; + + /** + * Wrap a function inside another to allow you to make adjustments to the parameters, or do other processing + * either before the internal function is called or with its results. + */ + wrap(fn: Function, wrapper: Function): Function; + + /** + * Creates a new list out of the two supplied by creating each possible pair from the lists. + */ + xprod(as: K[], bs: V[]): KeyValuePair[]; + xprod(as: K[]): (bs: V[]) => KeyValuePair[]; + + /** + * Creates a new list out of the two supplied by pairing up equally-positioned items from + * both lists. Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`. + */ + zip(list1: K[], list2: V[]): KeyValuePair[]; + zip(list1: K[]): (list2: V[]) => KeyValuePair[]; + + /** + * Creates a new object out of a list of keys and a list of values. + */ + // TODO: Dictionary as a return value is to specific, any seems to loose + zipObj(keys: string[], values: T[]): {[index:string]: T}; + zipObj(keys: string[]): (values: T[]) => {[index:string]: T}; + + + /** + * Creates a new list out of the two supplied by applying the function to each + * equally-positioned pair in the lists. + */ + zipWith(fn: (x: T, y: U) => TResult, list1: T[], list2: U[]): TResult[]; + zipWith(fn: (x: T, y: U) => TResult, list1: T[]): (list2: U[]) => TResult[]; + zipWith(fn: (x: T, y: U) => TResult): (list1: T[], list2: U[]) => TResult[]; + + } +} + +export = R; From 0b4348c5ed9aa385ec15aa139cea0c10ee3238db Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Tue, 16 Aug 2016 10:24:42 +0200 Subject: [PATCH 039/844] Moved amplitude-js definition to v2, because v3 is now available. --- amplitude-js/{ => v2}/amplitude-js-tests.ts | 0 amplitude-js/{ => v2}/amplitude-js.d.ts | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename amplitude-js/{ => v2}/amplitude-js-tests.ts (100%) rename amplitude-js/{ => v2}/amplitude-js.d.ts (100%) diff --git a/amplitude-js/amplitude-js-tests.ts b/amplitude-js/v2/amplitude-js-tests.ts similarity index 100% rename from amplitude-js/amplitude-js-tests.ts rename to amplitude-js/v2/amplitude-js-tests.ts diff --git a/amplitude-js/amplitude-js.d.ts b/amplitude-js/v2/amplitude-js.d.ts similarity index 100% rename from amplitude-js/amplitude-js.d.ts rename to amplitude-js/v2/amplitude-js.d.ts From 5c2eaa32e7f69b6f8193c6d1cb6ece6ff841c38d Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Tue, 16 Aug 2016 10:25:16 +0200 Subject: [PATCH 040/844] Removed redundant comment. --- amplitude-js/v2/amplitude-js.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/amplitude-js/v2/amplitude-js.d.ts b/amplitude-js/v2/amplitude-js.d.ts index 9a5df3d179..7cc031b34a 100644 --- a/amplitude-js/v2/amplitude-js.d.ts +++ b/amplitude-js/v2/amplitude-js.d.ts @@ -59,5 +59,3 @@ declare module amplitude { export var options: Config; } - -//declare var amplitude: AmplitudeStatic; From 62111c7509078492e169ec8a0ece6c30e88ab43b Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Tue, 16 Aug 2016 10:28:15 +0200 Subject: [PATCH 041/844] Converted tabs to 4-spaces. --- amplitude-js/v2/amplitude-js-tests.ts | 126 +++++++++++++------------- amplitude-js/v2/amplitude-js.d.ts | 86 +++++++++--------- 2 files changed, 106 insertions(+), 106 deletions(-) diff --git a/amplitude-js/v2/amplitude-js-tests.ts b/amplitude-js/v2/amplitude-js-tests.ts index 66285f10dd..3e69d7c867 100644 --- a/amplitude-js/v2/amplitude-js-tests.ts +++ b/amplitude-js/v2/amplitude-js-tests.ts @@ -3,85 +3,85 @@ /// module Amplitude.Tests { - function all() { - amplitude.init('YOUR_API_KEY_HERE', null, { - // optional configuration options - saveEvents: true, - includeUtm: true, - includeReferrer: true, - batchEvents: true, - eventUploadThreshold: 50 - }); - amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE', null, () => {}); + function all() { + amplitude.init('YOUR_API_KEY_HERE', null, { + // optional configuration options + saveEvents: true, + includeUtm: true, + includeReferrer: true, + batchEvents: true, + eventUploadThreshold: 50 + }); + amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE', null, () => {}); - amplitude.logEvent('EVENT_IDENTIFIER_HERE'); - amplitude.setUserId('USER_ID_HERE'); - amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE'); - amplitude.setUserId(null); // not string 'null' - amplitude.setVersionName('VERSION_NAME_HERE'); + amplitude.logEvent('EVENT_IDENTIFIER_HERE'); + amplitude.setUserId('USER_ID_HERE'); + amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE'); + amplitude.setUserId(null); // not string 'null' + amplitude.setVersionName('VERSION_NAME_HERE'); - amplitude.regenerateDeviceId(); - amplitude.setDeviceId('CUSTOM_DEVICE_ID'); + amplitude.regenerateDeviceId(); + amplitude.setDeviceId('CUSTOM_DEVICE_ID'); - amplitude.logEvent('EVENT_IDENTIFIER_HERE', { - 'color': 'blue', - 'age': 20, - 'key': 'value' - }); - amplitude.logEvent("EVENT_IDENTIFIER_HERE", null, (httpCode, response) => { }); + amplitude.logEvent('EVENT_IDENTIFIER_HERE', { + 'color': 'blue', + 'age': 20, + 'key': 'value' + }); + amplitude.logEvent("EVENT_IDENTIFIER_HERE", null, (httpCode, response) => { }); - let identify = new amplitude.Identify().set('gender', 'female').set('age', 20); - amplitude.identify(identify); + let identify = new amplitude.Identify().set('gender', 'female').set('age', 20); + amplitude.identify(identify); - identify = new amplitude.Identify().setOnce('sign_up_date', '08/24/2015'); - amplitude.identify(identify); + identify = new amplitude.Identify().setOnce('sign_up_date', '08/24/2015'); + amplitude.identify(identify); - identify = new amplitude.Identify().setOnce('sign_up_date', '09/14/2015'); - amplitude.identify(identify); + identify = new amplitude.Identify().setOnce('sign_up_date', '09/14/2015'); + amplitude.identify(identify); - identify = new amplitude.Identify().unset('gender').unset('age'); - amplitude.identify(identify); + identify = new amplitude.Identify().unset('gender').unset('age'); + amplitude.identify(identify); - identify = new amplitude.Identify().add('karma', 1).add('friends', 1); - amplitude.identify(identify); + identify = new amplitude.Identify().add('karma', 1).add('friends', 1); + amplitude.identify(identify); - identify = new amplitude.Identify().append('ab-tests', 'new-user-test').append('some_list', [1, 2, 3, 4, 'values']); - amplitude.identify(identify); + identify = new amplitude.Identify().append('ab-tests', 'new-user-test').append('some_list', [1, 2, 3, 4, 'values']); + amplitude.identify(identify); - identify = new amplitude.Identify().prepend('ab-tests', 'new-user-test').prepend('some_list', [1, 2, 3, 4, 'values']); - amplitude.identify(identify); + identify = new amplitude.Identify().prepend('ab-tests', 'new-user-test').prepend('some_list', [1, 2, 3, 4, 'values']); + amplitude.identify(identify); - identify = new amplitude.Identify() - .set('karma', 10) - .add('karma', 1) - .unset('karma'); - amplitude.identify(identify); + identify = new amplitude.Identify() + .set('karma', 10) + .add('karma', 1) + .unset('karma'); + amplitude.identify(identify); - identify = new amplitude.Identify() - .set('colors', ['rose', 'gold']) - .append('ab-tests', 'campaign_a') - .append('existing_list', [4, 5]); - amplitude.identify(identify); + identify = new amplitude.Identify() + .set('colors', ['rose', 'gold']) + .append('ab-tests', 'campaign_a') + .append('existing_list', [4, 5]); + amplitude.identify(identify); - amplitude.setUserProperties({ - gender: 'female', - age: 20 - }); + amplitude.setUserProperties({ + gender: 'female', + age: 20 + }); - amplitude.clearUserProperties(); + amplitude.clearUserProperties(); - amplitude.setOptOut(true); - amplitude.setOptOut(false); + amplitude.setOptOut(true); + amplitude.setOptOut(false); - amplitude.setGroup('orgId', '15'); - amplitude.setGroup('sport', ['soccer', 'tennis']); + amplitude.setGroup('orgId', '15'); + amplitude.setGroup('sport', ['soccer', 'tennis']); - // TODO: Implement those. - /* - var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3); - amplitude.logRevenueV2(revenue); + // TODO: Implement those. + /* + var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3); + amplitude.logRevenueV2(revenue); - amplitude.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' }); - */ - } + amplitude.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' }); + */ + } } diff --git a/amplitude-js/v2/amplitude-js.d.ts b/amplitude-js/v2/amplitude-js.d.ts index 7cc031b34a..613f5ad5d8 100644 --- a/amplitude-js/v2/amplitude-js.d.ts +++ b/amplitude-js/v2/amplitude-js.d.ts @@ -4,58 +4,58 @@ // Definitions: https://github.com/Asido/DefinitelyTyped declare module amplitude { - interface Config { - batchEvents?: boolean; - cookieExpiration?: number; - cookieName?: string; - deviceId?: string; - domain?: string; - eventUploadPeriodMillis?: number; - eventUploadThreshold?: number; - includeReferrer?: boolean; - includeUtm?: boolean; - language?: string; - optOut?: boolean; - platform?: string; - saveEvents?: boolean; - savedMaxCount?: number; - sessionTimeout?: number; - uploadBatchSize?: number; - } + interface Config { + batchEvents?: boolean; + cookieExpiration?: number; + cookieName?: string; + deviceId?: string; + domain?: string; + eventUploadPeriodMillis?: number; + eventUploadThreshold?: number; + includeReferrer?: boolean; + includeUtm?: boolean; + language?: string; + optOut?: boolean; + platform?: string; + saveEvents?: boolean; + savedMaxCount?: number; + sessionTimeout?: number; + uploadBatchSize?: number; + } - export class Identify { - set(key: string, value: any): Identify; - setOnce(key: string, value: any): Identify; - add(key: string, value: number): Identify; - append(key: string, value: any): Identify; - prepend(key: string, value: any): Identify; + export class Identify { + set(key: string, value: any): Identify; + setOnce(key: string, value: any): Identify; + add(key: string, value: number): Identify; + append(key: string, value: any): Identify; + prepend(key: string, value: any): Identify; - unset(key: string): Identify; - } + unset(key: string): Identify; + } - export function init(apiKey: string): void; - export function init(apiKey: string, userId: string): void; - export function init(apiKey: string, userId: string, options: Config): void; - export function init(apiKey: string, userId: string, options: Config, callback: () => void): void; + export function init(apiKey: string): void; + export function init(apiKey: string, userId: string): void; + export function init(apiKey: string, userId: string, options: Config): void; + export function init(apiKey: string, userId: string, options: Config, callback: () => void): void; - export function setVersionName(version: string): void; - export function setUserId(userId: string): void; + export function setVersionName(version: string): void; + export function setUserId(userId: string): void; - export function setDeviceId(id: string): void; - export function regenerateDeviceId(): void; + export function setDeviceId(id: string): void; + export function regenerateDeviceId(): void; - export function identify(identify: Identify): void; + export function identify(identify: Identify): void; - export function setUserProperties(properties: Object): void; - export function clearUserProperties(): void; + export function setUserProperties(properties: Object): void; + export function clearUserProperties(): void; - export function setOptOut(optOut: boolean): void; + export function setOptOut(optOut: boolean): void; - export function setGroup(groupType: string, groupName: string | string[]): void; + export function setGroup(groupType: string, groupName: string | string[]): void; - export function logEvent(event: string): void; - export function logEvent(event: string, data: Object): void; - export function logEvent(event: string, data: Object, callback: (httpCode: number, response: any) => void): void; + export function logEvent(event: string): void; + export function logEvent(event: string, data: Object): void; + export function logEvent(event: string, data: Object, callback: (httpCode: number, response: any) => void): void; - export var options: Config; + export var options: Config; } From 6d9768b337310fa80e348ed5da12d0547f5a5a52 Mon Sep 17 00:00:00 2001 From: Stephen Feest Date: Wed, 17 Aug 2016 10:03:38 +0100 Subject: [PATCH 042/844] Add additional $transclude function parameters A couple of additional optional parameters were added to the `$transclude` function when support for multi-slot transclusion was added in Angular 1.5 [1]. This commit updates the `ITranscludeFunction` type definition to reflect those changes. [1] https://docs.angularjs.org/api/ng/service/$compile#-controller- --- angularjs/angular.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 3c13fd6cf3..a6a130a66d 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1258,7 +1258,7 @@ declare namespace angular { // This corresponds to $transclude (and also the transclude function passed to link). interface ITranscludeFunction { // If the scope is provided, then the cloneAttachFn must be as well. - (scope: IScope, cloneAttachFn: ICloneAttachFunction): JQuery; + (scope: IScope, cloneAttachFn: ICloneAttachFunction, futureParentElement?: JQuery, slotName?: string): JQuery; // If one argument is provided, then it's assumed to be the cloneAttachFn. (cloneAttachFn?: ICloneAttachFunction): JQuery; } From 45f675a1624a24ef5bf20ec74bf7e90c3e56629e Mon Sep 17 00:00:00 2001 From: Ilia Choly Date: Wed, 17 Aug 2016 11:06:04 -0400 Subject: [PATCH 043/844] Add GoogleEarth type definitions --- google-earth/google-earth-tests.ts | 131 + google-earth/google-earth.d.ts | 3920 ++++++++++++++++++++++++++++ 2 files changed, 4051 insertions(+) create mode 100644 google-earth/google-earth-tests.ts create mode 100644 google-earth/google-earth.d.ts diff --git a/google-earth/google-earth-tests.ts b/google-earth/google-earth-tests.ts new file mode 100644 index 0000000000..6c9d4df1bf --- /dev/null +++ b/google-earth/google-earth-tests.ts @@ -0,0 +1,131 @@ +/// + +google.load("earth", "1", {"other_params":"sensor=true_or_false"}); + +google.earth.createInstance("map3d", initCB, failureCB); + +function failureCB(error: any) {} + +function initCB(ge: google.earth.GEPlugin) { + + ge.getWindow().setVisibility(true); + + + // Create the placemark. + var placemark = ge.createPlacemark(''); + placemark.setName("placemark"); + + // Set the placemark's location. + var point = ge.createPoint(''); + point.setLatitude(12.345); + point.setLongitude(54.321); + placemark.setGeometry(point); + + // Create a style map. + var styleMap = ge.createStyleMap(''); + + // Create normal style for style map. + var normalStyle = ge.createStyle(''); + var normalIcon = ge.createIcon(''); + normalIcon.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png'); + normalStyle.getIconStyle().setIcon(normalIcon); + + // Create highlight style for style map. + var highlightStyle = ge.createStyle(''); + var highlightIcon = ge.createIcon(''); + highlightIcon.setHref('http://google-maps-icons.googlecode.com/files/girlfriend.png'); + highlightStyle.getIconStyle().setIcon(highlightIcon); + highlightStyle.getIconStyle().setScale(5.0); + + styleMap.setNormalStyle(normalStyle); + styleMap.setHighlightStyle(highlightStyle); + + // Apply stylemap to a placemark. + placemark.setStyleSelector(styleMap); + + //Add the placemark to Earth. + ge.getFeatures().appendChild(placemark); + + + // balloons + var balloon = ge.createHtmlDivBalloon(''); + balloon.setFeature(placemark); + var div = document.createElement('DIV'); + div.innerHTML = 'Any HTML, CSS, or JavaScript goes here.'; + balloon.setContentDiv(div); + ge.setBalloon(balloon); + + // Create the ScreenOverlay + var screenOverlay = ge.createScreenOverlay(''); + + // Specify a path to the image and set as the icon + var icon = ge.createIcon(''); + icon.setHref('http://www.google.com/intl/en_ALL/images/logo.gif'); + screenOverlay.setIcon(icon); + + // Set the ScreenOverlay's position in the window + screenOverlay.getOverlayXY().setXUnits(ge.UNITS_PIXELS); + screenOverlay.getOverlayXY().setYUnits(ge.UNITS_PIXELS); + screenOverlay.getOverlayXY().setX(200); + screenOverlay.getOverlayXY().setY(200); + + // Set the overlay's size in pixels + screenOverlay.getSize().setXUnits(ge.UNITS_PIXELS); + screenOverlay.getSize().setYUnits(ge.UNITS_PIXELS); + screenOverlay.getSize().setX(250); + screenOverlay.getSize().setY(75); + + // Specify the point in the image around which to rotate + screenOverlay.getRotationXY().setXUnits(ge.UNITS_FRACTION); + screenOverlay.getRotationXY().setYUnits(ge.UNITS_FRACTION); + screenOverlay.getRotationXY().setX(0.5); + screenOverlay.getRotationXY().setY(0.5); + + // Rotate the overlay + screenOverlay.setRotation(25); + + // Add the ScreenOverlay to Earth + ge.getFeatures().appendChild(screenOverlay); + + + // network link + var link = ge.createLink(''); + var href = 'http://code.google.com/' + + 'apis/earth/documentation/samples/kml_example.kml' + link.setHref(href); + + var networkLink = ge.createNetworkLink(''); + networkLink.set(link, true, true); // Sets the link, refreshVisibility, and flyToView + + ge.getFeatures().appendChild(networkLink); + + // Get the current view. + var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND); + + // Set new latitude and longitude values. + lookAt.setLatitude(36.584207); + lookAt.setLongitude(-121.754322); + + // Update the view in Google Earth. + ge.getView().setAbstractView(lookAt); + + // time + ge.getTime().getControl().setVisibility(ge.VISIBILITY_SHOW); + ge.getTime().setHistoricalImageryEnabled(true); + var extents = ge.getTime().getControl().getExtents(); + var begin = extents.getBegin().get(); + var end = extents.getEnd().get(); + + // tour + ge.getTourPlayer().play(); + + + // controls + ge.getNavigationControl().getScreenXY().setXUnits(ge.UNITS_INSET_PIXELS); + ge.getNavigationControl().getScreenXY().setYUnits(ge.UNITS_PIXELS); + + + // sky + ge.getOptions().setMapType(ge.MAP_TYPE_SKY); + ge.getOptions().setMapType(ge.MAP_TYPE_EARTH); +} diff --git a/google-earth/google-earth.d.ts b/google-earth/google-earth.d.ts new file mode 100644 index 0000000000..ac10729f17 --- /dev/null +++ b/google-earth/google-earth.d.ts @@ -0,0 +1,3920 @@ +// Type definitions for Google Earth Plugin +// Project: https://developers.google.com/earth/ +// Definitions by: Ilia Choly +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace google { + + export function load( + moduleName: string, + moduleVersion: string, + optionalSettings?: any + ): void; +} + +declare namespace google.earth { + + /** + * Whether or not the Google Earth Browser Plug-in and API are supported on the current browser and operating system. + */ + export function isSupported(): boolean; + + /** + * Whether or not the Google Earth Browser Plug-in is currently installed on the user's machine. + * + * Note: if the plug-in is not installed, the user will be presented with a 'download' link upon calls to google.earth.createInstance(). + */ + export function isInstalled(): boolean; + + /** + * Attempts to create an instance of the plugin under the given web browser HTML DOM node. + * Upon success, calls the function passed in as the initCallback argument. + * Upon failure, calls the function passed in as the failureCallback argument and displays an error message to the user in place of the plug-in object. + * + * Note: + * + * The HTML DOM must be loaded before this function can be called. + * Common usage is to call this function upon the 's load event, or to use google.setOnLoadCallback. + */ + export function createInstance( + domNode: string|Element, + initCallback: (plugin: GEPlugin) => void, + failureCallback: (error: any) => void, + options?: any + ): void; + + /** + * Attaches a listener to a given object for a specific event; when the event occurs on the object, the given callback is invoked. + */ + export function addEventListener( + targetObject: any, + eventID: string, + listenerCallback: (event: KmlEvent) => void, + useCapture?: boolean + ): void; + + /** + * Removes an event listener previously added using google.earth.addEventListener() from the event chain. + * + * Note: + * + * You must pass in the exact same function object as was passed to addEventListener. + * If you are using an anonymous function callback, it will need to be refactored into its own variable. + */ + export function removeEventListener( + targetObject: any, + eventID: string, + listenerCallback: (event: KmlEvent) => void, + useCapture?: boolean + ): void; + + /** + * Retrieves and parses a KML or KMZ file at the given URL and returns an instance of a KmlFeature-derived class representing the parsed KML object model. + * + * Note: This function does not display the feature on the Earth. See below for more information. + */ + export function fetchKml( + pluginInstance: GEPlugin, + url: string, + completionCallback: (feature: KmlFeature) => void + ): void; + + /** + * Efficiently executes an arbitrary, user-defined function (the batch function), minimizing the amount of overhead incurred during cross-process communication between the web browser and Google Earth Plugin. + * This method is useful for batching together a large set of calls to the Earth API, for example, a large number of consecutive calls to KmlCoordArray.pushLatLngAlt. + */ + export function executeBatch(pluginInstance: GEPlugin, batchFunction: Function): void; + + /** + * Sets the language to be used for new instances of the plugin. + * Needs to be called before google.earth.createInstance(). + * Affects road and border labels, the error message displayed when the plugin fails to load, as well as the language of the Terms of Use page linked from the plugin. + */ + export function setLanguage(languageCode: string): void; + + /** + * This interface enables programmatic and user-driven interaction with photo overlays in the Google Earth Plugin. + * + * Note: This interface is still under development. + */ + export class GEPhotoOverlayViewer { + + /** + * Enters the given photo overlay object, exiting any other currently active photo overlay. + * If the argument is null, then any currently active photo overlay is exited and normal global navigation is enabled. + */ + setPhotoOverlay(photoOverlay: KmlPhotoOverlay): void; + } + + /** + * Used to manipulate the navigation controls in Google Earth. + */ + export class GENavigationControl { + + /** + * Whether the control is always visible, always hidden, or visible only when the user intends to use the control. + * + * See also: + * + * * GEPlugin.VISIBILITY_SHOW + * * GEPlugin.VISIBILITY_HIDE + * * GEPlugin.VISIBILITY_AUTO + */ + getVisibility(): GEVisibilityEnum; + + /** + * Whether the control is always visible, always hidden, or visible only when the user intends to use the control. + * + * See also: + * + * * GEPlugin.VISIBILITY_SHOW + * * GEPlugin.VISIBILITY_HIDE + * * GEPlugin.VISIBILITY_AUTO + */ + setVisibility(visibility: GEVisibilityEnum): void; + + /** + * Specifies the size of the navigation control. + * + * See also: + * + * * GEPlugin.NAVIGATION_CONTROL_LARGE + * * GEPlugin.NAVIGATION_CONTROL_SMALL + */ + getControlType(): GENavigationControlEnum; + + /** + * Specifies the size of the navigation control. + * + * See also: + * + * * GEPlugin.NAVIGATION_CONTROL_LARGE + * * GEPlugin.NAVIGATION_CONTROL_SMALL + */ + setControlType(controlType: GENavigationControlEnum): void; + + /** + * The position of the navigation controls in Google Earth + */ + getScreenXY(): KmlVec2; + + /** + * Enables or disables user-initiated entry to Street View imagery. + * When true, the Pegman icon is present in the navigation controls, allowing a user to drag the Pegman onto a street to initiate Street View. + * Users can also zoom down to ground level to enter Street View when this is set to true. + */ + setStreetViewEnabled(streetViewEnabled: boolean): void; + + /** + * Whether Street View is enabled in the navigation controls. + */ + getStreetViewEnabled(): boolean; + } + + /** + * Defines a tour, which is a playlist of scripted camera and update events. + * + * Note: This interface is still under development. + */ + export class KmlTour extends KmlFeature {} + + /** + * This interface enables programmatic and user-driven interaction with KML tours in the Google Earth Plugin. + * + * Note: This interface is still under development. + */ + export class GETourPlayer { + + /** + * Enters the given tour object, exiting any other currently active tour. + * This method does not automatically begin playing the tour. + * If the argument is null, then any currently active tour is exited and normal globe navigation is enabled. + */ + setTour(tour: KmlTour): void; + + /** + * Plays the currently active tour. + */ + play(): void; + + /** + * Pauses the currently active tour. + */ + pause(): void; + + /** + * Resets the currently active tour, stopping playback and rewinding to the start of the tour. + */ + reset(): void; + + /** + * The current elapsed playing time of the active tour, in seconds. + */ + getCurrentTime(): number; + + /** + * The current elapsed playing time of the active tour, in seconds. + */ + setCurrentTime(currentTime: number): void; + + /** + * The total duration of the active tour, in seconds. If no tour is loaded, the behavior of this method is undefined. + */ + getDuration(): number; + } + + /** + * This interface contains result information obtained by calling GEView's hitTest method. + * + * See also: + * + * * GEView.hitTest + */ + export class GEHitTestResult { + + /** + * Latitude of sampled point. + */ + getLatitude(): number; + + /** + * Latitude of sampled point. + */ + setLatitude(latitude: number): void; + + /** + * Longitude of sampled point. + */ + getLongitude(): number; + + /** + * Longitude of sampled point. + */ + setLongitude(longitude: number): void; + + /** + * Altitude of sampled point. + */ + getAltitude(): number; + + /** + * Altitude of sampled point. + */ + setAltitude(altitude: number): void; + } + + /** + * Maps between two different icon styles. + * Typically this interface is used to provide separate normal and highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon. + */ + export class KmlStyleMap extends KmlStyleSelector { + + /** + * Sets both URLs for the placemark style. + */ + setUrl(normalStyleUrl: string, highlightStyleUrl: string): void; + + /** + * Sets both placemark styles. + */ + setStyle(normalStyle: KmlStyle, highlightStyle: KmlStyle): void; + + /** + * Defines a normal style for a placemark. + */ + getNormalStyleUrl(): string; + + /** + * Defines a normal style for a placemark. + */ + setNormalStyleUrl(normalStyleUrl: string): void; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + getHighlightStyleUrl(): string; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + setHighlightStyleUrl(highlightStyleUrl: string): void; + + /** + * Defines a normal style for a placemark. + */ + getNormalStyle(): KmlStyle; + + /** + * Defines a normal style for a placemark. + */ + setNormalStyle(normalStyle: KmlStyle): void; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + getHighlightStyle(): KmlStyle; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + setHighlightStyle(highlightStyle: KmlStyle): void; + } + + /** + * References a KML file or KMZ archive on a remote network. + * Use the Link property to specify the location of the KML file. + * Within that property, you can define the refresh options for updating the file, based on time and camera change. + * NetworkLinks can be used in combination with Regions to handle very large datasets efficiently. + */ + export class KmlNetworkLink extends KmlFeature { + + /** + * Sets the link, refreshVisibility, and flyToView for the network link. + */ + set(link: KmlLink, refreshVisibility: boolean, flyToView: boolean): void; + + /** + * Specifies the location of any of the following: + * + * * KML files fetched by network links + * * Image files used by icons in icon styles, ground overlays, and screen overlays + * * Model files used in the Model object + */ + getLink(): KmlLink; + + /** + * Specifies the location of any of the following: + * + * * KML files fetched by network links + * * Image files used by icons in icon styles, ground overlays, and screen overlays + * * Model files used in the Model object + */ + setLink(link: KmlLink): void; + + /** + * A value of 0 leaves the visibility of features within the control of the Google Earth user. + * Set the value to 1 to reset the visibility of features each time the NetworkLink is refreshed. + * For example, suppose a Placemark within the linked KML file has visibility set to 1 and the NetworkLink has refreshVisibility set to 1. + * When the file is first loaded into Google Earth, the user can clear the check box next to the item to turn off display in the 3D viewer. + * However, when the NetworkLink is refreshed, the Placemark will be made visible again, since its original visibility state was TRUE. + */ + getRefreshVisibility(): boolean; + + /** + * A value of 0 leaves the visibility of features within the control of the Google Earth user. + * Set the value to 1 to reset the visibility of features each time the NetworkLink is refreshed. + * For example, suppose a Placemark within the linked KML file has visibility set to 1 and the NetworkLink has refreshVisibility set to 1. + * When the file is first loaded into Google Earth, the user can clear the check box next to the item to turn off display in the 3D viewer. + * However, when the NetworkLink is refreshed, the Placemark will be made visible again, since its original visibility state was TRUE. + */ + setRefreshVisibility(refreshVisibility: boolean): void; + + /** + * A value of 1 causes Google Earth to fly to the view of the LookAt or Camera in the NetworkLinkControl (if it exists). + */ + getFlyToView(): boolean; + + /** + * A value of 1 causes Google Earth to fly to the view of the LookAt or Camera in the NetworkLinkControl (if it exists). + */ + setFlyToView(flyToView: boolean): void; + } + + /** + * Draws an image overlay fixed to the screen. + * Sample uses for ScreenOverlays are compasses, logos, and heads-up displays. + * ScreenOverlay sizing is determined by the size element. + * Positioning of the overlay is handled by mapping a point in the image specified by screenXY to a point on the screen specified by overlayXY. + * Then the image is rotated by rotation degrees about a point relative to the screen specified by rotationXY. + * + * Note: + * + * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. + * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. + */ + export class KmlScreenOverlay extends KmlOverlay { + + /** + * Specifies a point on (or outside of) the overlay image that is mapped to the screen coordinate. + * It requires x and y values, and the units for those values. + * + * Note: + * + * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. + * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. + */ + getScreenXY(): KmlVec2; + + /** + * Specifies a point relative to the screen origin that the overlay image is mapped to. + * The x and y values can be specified in three different ways: as pixels ("pixels"), as fractions of the screen ("fraction"), or as inset pixels ("insetPixels"), which is an offset in pixels from the upper right corner of the screen. + * The x and y positions can be specified in different ways - for example, x can be in pixels and y can be a fraction. + * The origin of the coordinate system is in the lower left corner of the screen. + * + * Note: + * + * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. + * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. + */ + getOverlayXY(): KmlVec2; + + /** + * Point relative to the screen about which the screen overlay is rotated. + */ + getRotationXY(): KmlVec2; + + /** + * Specifies the size of the image for the screen overlay, as follows: + * + * * A value of -1 indicates to use the native dimension + * * A value of 0 indicates to maintain the aspect ratio + * * A value of n sets the value of the dimension + */ + getSize(): KmlVec2; + + /** + * Adjusts how the image is placed inside the field of view. + * This element is useful if your image has been rotated and deviates slightly from a desired horizontal view. + */ + getRotation(): number; + + /** + * Adjusts how the image is placed inside the field of view. + * This element is useful if your image has been rotated and deviates slightly from a desired horizontal view. + */ + setRotation(rotation: number): void; + } + + /** + * Defines a photo overlay, which is a geographically located photograph of the Earth. + * Photo overlays can be drawn onto 2D rectangles in three dimensional space, or in the case of panoramic photos, onto partial or full cylinders, or even spheres. + * + * Note: This interface is still under development. + */ + export class KmlPhotoOverlay extends KmlOverlay {} + + /** + * Draws an image overlay draped onto the terrain. + * The href child of Icon specifies the image to be used as the overlay. + * If this object is omitted or contains no href, a rectangle is drawn using the color defined by the overlay. + */ + export class KmlGroundOverlay extends KmlOverlay { + + /** + * Specifies the distance above the earth's surface. + */ + getAltitude(): number; + + /** + * Specifies the distance above the earth's surface. + */ + setAltitude(altitude: number): void; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + + /** + * The bounding box of the ground overlay. + */ + getLatLonBox(): KmlLatLonBox; + + /** + * The bounding box of the ground overlay. + */ + setLatLonBox(latLonBox: KmlLatLonBox): void; + } + + /** + * The KmlOverlay object is an abstract object and cannot be used directly in a KML file. + * Overlay is the base type for image overlays drawn on the planet surface or on the screen. + * Icon specifies the image to use and can be configured to reload images based on a timer or by camera changes. + * This object also includes specifications for stacking order of multiple overlays and for adding color and transparency values to the base image. + */ + export class KmlOverlay extends KmlFeature { + + /** + * Specifies the color values. + */ + getColor(): KmlColor; + + /** + * Defines the stacking order for the images in overlapping overlays. + * Overlays with higher drawOrder values are drawn on top of overlays with lower drawOrder values. + */ + getDrawOrder(): number; + + /** + * Defines the stacking order for the images in overlapping overlays. + * Overlays with higher drawOrder values are drawn on top of overlays with lower drawOrder values. + */ + setDrawOrder(drawOrder: number): void; + + /** + * Defines the image associated with the Overlay. + */ + getIcon(): KmlIcon; + + /** + * Defines the image associated with the Overlay. + */ + setIcon(icon: KmlIcon): void; + } + + /** + * This class controls the display of sunlight, historical imagery, and Street View panoramas in the plugin. + * The KmlViewerOptions object is passed to KmlAbstractView.setViewerOptions() + */ + export class KmlViewerOptions extends KmlObject { + + /** + * Returns the current state of the specified viewer option type. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + * * GEPlugin.OPTION_STATE_DEFAULT + * * GEPlugin.OPTION_STATE_ENABLED + * * GEPlugin.OPTION_STATE_DISABLED + */ + setOption(type: GEViewerOptionsTypeEnum, state: GEViewerOptionsValueEnum): void; + + /** + * Set the state of viewer options, including sunlight, Street View, and historical imagery. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + * * GEPlugin.OPTION_STATE_DEFAULT + * * GEPlugin.OPTION_STATE_ENABLED + * * GEPlugin.OPTION_STATE_DISABLED + */ + getOption(type: GEViewerOptionsValueEnum): GEViewerOptionsValueEnum; + } + + /** + * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + export class KmlOrientation extends KmlObject { + + /** + * Sets the heading, tilt, and roll of a model. + */ + set(heading: number, tilt: number, roll: number): void; + + /** + * Rotation about the z axis (normal to the Earth's surface). + * A value of 0 (the default) equals North. + * A positive rotation is clockwise around the z axis and specified in degrees from 0 to 360. + */ + getHeading(): number; + + /** + * Rotation about the z axis (normal to the Earth's surface). + * A value of 0 (the default) equals North. + * A positive rotation is clockwise around the z axis and specified in degrees from 0 to 360. + */ + setHeading(heading: number): void; + + /** + * Rotation about the x axis. + * A positive rotation is clockwise around the x axis and specified in degrees from 0 to 360. + */ + getTilt(): number; + + /** + * Rotation about the x axis. + * A positive rotation is clockwise around the x axis and specified in degrees from 0 to 360. + */ + setTilt(tilt: number): void; + + /** + * Rotation about the y axis. + * A positive rotation is clockwise around the y axis and specified in degrees from 0 to 360. + */ + getRoll(): number; + + /** + * Rotation about the y axis. + * A positive rotation is clockwise around the y axis and specified in degrees from 0 to 360. + */ + setRoll(roll: number): void; + } + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + export class KmlLocation extends KmlObject { + + /** + * Sets the latitude, longitude, and altitude of the Model. + */ + setLatLngAlt(lat: number, lng: number, alt: number): void; + + /** + * Longitude of the Model's location. + * Angular distance in degrees, relative to the Prime Meridian. + * Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + getLongitude(): number; + + /** + * Longitude of the Model's location. + * Angular distance in degrees, relative to the Prime Meridian. + * Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + setLongitude(longitude: number): void; + + /** + * Latitude of the camera location. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLatitude(): number; + + /** + * Latitude of the camera location. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLatitude(latitude: number): void; + + /** + * Specifies the distance above the earth's surface. + */ + getAltitude(): number; + + /** + * Specifies the distance above the earth's surface. + */ + setAltitude(altitude: number): void; + } + + /** + * Scales a model along the x, y, and z axes in the model's coordinate space. + */ + export class KmlScale extends KmlObject { + + /** + * Sets the x, y, and z coordinates for a model. + */ + set(x: number, y: number, z: number): void; + + /** + * Indicates the x coordinate. + */ + getX(): number; + + /** + * Indicates the x coordinate. + */ + setX(x: number): void; + + /** + * Indicates the y coordinate. + */ + getY(): number; + + /** + * Indicates the y coordinate. + */ + setY(y: number): void; + + /** + * Indicates the z coordinate. + */ + getZ(): number; + + /** + * Indicates the z coordinate. + */ + setZ(z: number): void; + } + + /** + * A single tuple consisting of floating point values for longitude, latitude, and altitude (in that order). + * Longitude and latitude values are in degrees. + * + * * longitude = -180 and <= 180 + * * latitude = -90 and = 90 + * * altitude values (optional) are in meters above sea level + */ + export class KmlCoord { + + /** + * Sets the latitude, longitude, altitude. + */ + setLatLngAlt(latitude: number, longitude: number, altitude: number): void; + + /** + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLatitude(): number; + + /** + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLatitude(latitude: number): void; + + /** + * Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + getLongitude(): number; + + /** + * Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + setLongitude(longitude: number): void; + + /** + * Distance from the earth's surface. + */ + getAltitude(): number; + + /** + * Distance from the earth's surface. + */ + setAltitude(altitude: number): void; + } + + /** + * The KmlCoordArray object defines an array of coordinates. + */ + export class KmlCoordArray { + + /** + * Returns the coordinates at the given index. + */ + get(index: number): KmlCoord; + + /** + * Sets the coordinates at the given index.. + */ + set(index: number, coord: KmlCoord): void; + + /** + * Sets the latitude, longitude, and altitude. + */ + setLatLngAlt( + index: number, + latitude: number, + longitude: number, + altitude: number + ): void; + + /** + * Appends one or more new elements to the end of an array and returns the new length of the array. + */ + pushLatLngAlt( + latitude: number, + longitude: number, + altitude: number + ): void; + + /** + * Appends one or more new elements to the end of an array and returns the new length of the array. + */ + push(coordOrList: KmlCoord): void; + + /** + * Deletes the last element of an array, decrements the array length, and returns the value that is removed. + */ + pop(): KmlCoord; + + /** + * Adds an element or elements to the beginning of an array. + */ + unshift(coordOrList: KmlCoord): number; + + /** + * Adds an element or elements to the beginning of an array. + */ + unshiftLatLngAlt( + latitude: number, + longitude: number, + altitude: number + ): void; + + /** + * Removes and returns the first element of the array. + */ + shift(): KmlCoord; + + /** + * Reverses the order of the elements in the array. + */ + reverse(): void; + + /** + * Clears all of the elements in the array + */ + clear(): void; + + /** + * Specifies the length of the index array. + */ + getLength(): number; + } + + /** + * The object corresponding to the retangular region in which Google Earth is displayed. + */ + export class GEWindow extends GEEventEmitter { + + /** + * Gives the Google Earth object focus. + */ + focus(): void; + + /** + * Removes focus from the Google Earth object. + */ + blur(): void; + + /** + * Toggles the overall visibility of Google Earth inside the browser. + */ + getVisibility(): boolean; + + /** + * Toggles the overall visibility of Google Earth inside the browser. + */ + setVisibility(visibility: boolean): void; + } + + /** + * The GEGlobe class encapsulates the Google Earth globe to determine access and event behavior. + */ + export class GEGlobe extends KmlObject { + + /** + * Returns the altitude for a given location on the globe. + * If the altitude data for the location has not yet been loaded, the return value is 0. + */ + getGroundAltitude(lat: number, lon: number): number; + + /** + * The top-level features currently in the Earth instance. + */ + getFeatures(): GEFeatureContainer; + } + + /** + * Controls the behavior of the camera that views the scene in Google Earth. + */ + export class GEView { + + /** + * Returns the screen x,y coordinates of a given point on the globe. + * + * Tip: project() is the inverse of hitTest(). + * + * See also: + * + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + project( + lat: number, + lng: number, + alt: number, + altitudeMode: KmlAltitudeModeEnum + ): KmlVec2; + + /** + * Sets the camera that views the scene in Google Earth. + */ + setAbstractView(view: KmlAbstractView): void; + + /** + * Creates and returns a new KmlLookAt object, initialized to the current camera position and orientation. + * Use 'altitudeMode' to specify the altitude mode of the looked-at point. + * + * See also: + * + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + copyAsLookAt(altitudeMode: KmlAltitudeModeEnum): KmlLookAt; + + /** + * Creates and returns a new KmlCamera object, initialized to the current camera position and orientation. + * Use 'altitudeMode' to specify the altitude mode of the new camera. + * + * See also: + * + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + copyAsCamera(altitudeMode: KmlAltitudeModeEnum): KmlCamera; + + /** + * Returns a bounding box that completely contains the region of the globe that is currently visible. + * The returned box will be larger than what is strictly visible, if that is necessary to include everything that is visible. + */ + getViewportGlobeBounds(): KmlLatLonBox; + + /** + * Given a point on the screen in pixel coordinates, returns a GEHitTestResult with information about the geographic location corresponding to the point on the screen. + * Tip: hitTest() is the inverse of project(). + * + * See also: + * + * * GEPlugin.UNITS_PIXELS + * * GEPlugin.UNITS_INSET_PIXELS + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.HIT_TEST_GLOBE + * * GEPlugin.HIT_TEST_TERRAIN + * * GEPlugin.HIT_TEST_BUILDINGS + */ + hitTest( + x: number, + xUnits: KmlUnitsEnum, + y: number, + yUnits: KmlUnitsEnum, + mode: GEHitTestModeEnum + ): GEHitTestResult; + } + + /** + * Defines an image associated with an Icon style or overlay. + */ + export class KmlIcon extends KmlLink { + + /** + * Gets the offset from the left (), in pixels, of the icon. + */ + getX(): number; + + /** + * Specifies the icon's offset (), in pixels from the left side of its icon palette, if a palette has been specified in the element. + */ + setX(x: number): number; + + /** + * Gets the offset from the bottom (), in pixels, of the icon. + */ + getY(): number; + + /** + * Specifies the offset (), in pixels from the bottom of its icon palette, if a palette has been specified in the element. + */ + setY(y: number): void; + + /** + * Gets the width (), in pixels, of the icon. + */ + getW(): number; + + /** + * Specifies the width (), in pixels, of the icon to use. + */ + setW(w: number): void; + + /** + * Gets the height (), in pixels, of the icon. + */ + getH(): number; + + /** + * Specifies the height (), in pixels, of the icon to use. + */ + setH(h: number): void; + } + + /** + * Specifies the location of any KML files fetched by network links, image files used by icons in icon styles, ground overlays, and screen overlays, or model files used in the Model object. + */ + export class KmlLink extends KmlObject { + + /** + * A URL (either an HTTP address or a local file specification). + * When the parent of Link is a NetworkLink, href is a KML file. + * When the parent of Link is a Model, href is a COLLADA file. + * When the parent of Link is an Overlay, href is an image. + */ + getHref(): string; + + /** + * A URL (either an HTTP address or a local file specification). + * When the parent of Link is a NetworkLink, href is a KML file. + * When the parent of Link is a Model, href is a COLLADA file. + * When the parent of Link is an Overlay, href is an image. + */ + setHref(href: string): void; + + /** + * Specifies to use a time-based refresh mode. + * + * See also: + * + * * GEPlugin.REFRESH_ON_CHANGE + * * GEPlugin.REFRESH_ON_INTERVAL + * * GEPlugin.REFRESH_ON_EXPIRE + */ + getRefreshMode(): KmlRefreshModeEnum; + + /** + * Specifies to use a time-based refresh mode. + * + * See also: + * + * * GEPlugin.REFRESH_ON_CHANGE + * * GEPlugin.REFRESH_ON_INTERVAL + * * GEPlugin.REFRESH_ON_EXPIRE + */ + setRefreshMode(refreshMode: KmlRefreshModeEnum): void; + + /** + * Indicates to refresh the file every n seconds. + */ + getRefreshInterval(): number; + + /** + * Indicates to refresh the file every n seconds. + */ + setRefreshInterval(refreshInterval: number): void; + + /** + * Specifies how the link is refreshed when the viewport changes. + * + * See also: + * + * * GEPlugin.VIEW_REFRESH_NEVER + * * GEPlugin.VIEW_REFRESH_ON_STOP + * * GEPlugin.VIEW_REFRESH_ON_REGION + */ + getViewRefreshMode(): KmlViewRefreshModeEnum; + + /** + * Specifies how the link is refreshed when the viewport changes. + * + * See also: + * + * * GEPlugin.VIEW_REFRESH_NEVER + * * GEPlugin.VIEW_REFRESH_ON_STOP + * * GEPlugin.VIEW_REFRESH_ON_REGION + */ + setViewRefreshMode(viewRefreshMode: KmlViewRefreshModeEnum): void; + + /** + * Specifies how the link is refreshed when the camera changes. + */ + getViewRefreshTime(): number; + + /** + * Specifies how the link is refreshed when the camera changes. + */ + setViewRefreshTime(viewRefreshTime: number): void; + + /** + * Scales the BBOX parameters before sending them to the server. + * A value less than 1 specifies to use less than the full view (screen). + * A value greater than 1 specifies to fetch an area that extends beyond the edges of the current view. + */ + getViewBoundScale(): number; + + /** + * Scales the BBOX parameters before sending them to the server. + * A value less than 1 specifies to use less than the full view (screen). + * A value greater than 1 specifies to fetch an area that extends beyond the edges of the current view. + */ + setViewBoundScale(viewBoundScale: number): void; + + /** + * Specifies the format of the query string that is appended to the Link's href before the file is fetched. + * (If the href specifies a local file, this element is ignored.) + */ + getViewFormat(): string; + + /** + * Specifies the format of the query string that is appended to the Link's href before the file is fetched. + * (If the href specifies a local file, this element is ignored.) + */ + setViewFormat(viewFormat: string): void; + } + + /** + * Controls time in the plugin. + */ + export class GETime { + + /** + * Set the plugin's clock rate. + * A value of 1 corresponds with real time; to pass one year in the plugin for every real second, set the rate to 31536000 (60 times 60 times 24 times 365). + */ + setRate(rate: number): void; + + /** + * Get the current plugin clock rate. + */ + getRate(): number; + + /** + * Returns the current computer clock time as a KmlTimeStamp object. + */ + getSystemTime(): KmlTimeStamp; + + /** + * Returns the GETimeControl object; this is the time slider. + */ + getControl(): GETimeControl; + + /** + * Whether or not historical imagery is enabled. + */ + getHistoricalImageryEnabled(): boolean; + + /** + * Turn historical imagery on or off. + * For more information, read the Time chapter of the Developer's Guide. + */ + setHistoricalImageryEnabled(historicalImageryEnabled: boolean): void; + + /** + * Get the current plugin time as a KmlTimeStamp or KmlTimeSpan. + */ + getTimePrimitive(): KmlTimePrimitive; + + /** + * Sets the current plugin time. + */ + setTimePrimitive(timePrimitive: KmlTimePrimitive): void; + } + + /** + * Used to manipulate the behavior of the Google Earth options such as, navigation, flyToSpeed, scroll wheel speed and so on. + */ + export class GEOptions { + + /** + * Sets the map type to Earth or sky mode. + */ + setMapType(type: GEMapTypeEnum): void; + + /** + * Speed of zoom when user rolls the mouse wheel. Default is 1. + * Set to a negative number to reverse the zoom direction. + */ + getScrollWheelZoomSpeed(): number; + + /** + * Speed of zoom when user rolls the mouse wheel. Default is 1. + * Set to a negative number to reverse the zoom direction. + */ + setScrollWheelZoomSpeed(scrollWheelZoomSpeed: number): void; + + /** + * Specifies the speed at which the camera moves (0 to 5.0). + * Set to SPEED_TELEPORT to immediately appear at selected destination. + * + * See also: + * + * * GEPlugin.SPEED_TELEPORT + */ + getFlyToSpeed(): number; + + /** + * Specifies the speed at which the camera moves (0 to 5.0). + * Set to SPEED_TELEPORT to immediately appear at selected destination. + * + * See also: + * + * * GEPlugin.SPEED_TELEPORT + */ + setFlyToSpeed(flyToSpeed: number): void; + + /** + * Show or hide the status bar. Disabled by default. + */ + getStatusBarVisibility(): boolean; + + /** + * Show or hide the status bar. Disabled by default. + */ + setStatusBarVisibility(statusBarVisibility: boolean): void; + + /** + * Show or hide the grid. Disabled by default. + */ + getGridVisibility(): boolean; + + /** + * Show or hide the grid. Disabled by default. + */ + setGridVisibility(gridVisibility: boolean): void; + + /** + * Show or hide the overview map. Disabled by default. + */ + getOverviewMapVisibility(): boolean; + + /** + * Show or hide the overview map. Disabled by default. + */ + setOverviewMapVisibility(overviewMapVisibility: boolean): void; + + /** + * Show or hide the scale legend. Disabled by default. + */ + getScaleLegendVisibility(): boolean; + + /** + * Show or hide the scale legend. Disabled by default. + */ + setScaleLegendVisibility(scaleLegendVisibility: boolean): void; + + /** + * Show or hide the blue atmosphere that appears around the perimeter of the Earth. + * On by default. + */ + getAtmosphereVisibility(): boolean; + + /** + * Show or hide the blue atmosphere that appears around the perimeter of the Earth. + * On by default. + */ + setAtmosphereVisibility(atmosphereVisibility: boolean): void; + + /** + * Enable or disable user panning and zooming of the map. Enabled by default. + * + * Note: This also enables and disables keyboard navigation (arrow keys, page-up/page-down, etc). + */ + getMouseNavigationEnabled(): boolean; + + /** + * Enable or disable user panning and zooming of the map. Enabled by default. + * + * Note: This also enables and disables keyboard navigation (arrow keys, page-up/page-down, etc). + */ + setMouseNavigationEnabled(mouseNavigationEnabled: boolean): void; + + /** + * Returns true if the animation of features as they are added or removed from the globe has been enabled. + */ + getFadeInOutEnabled(): boolean; + + /** + * Enable or disable the animation of a feature when it is added or removed from the Google Earth plugin. + * The animation consists of a slight change of scale. Default is true. + */ + setFadeInOutEnabled(fadeInOutEnabled: boolean): void; + + /** + * Returns true if display units are set to imperial units (feet and miles). + * False denotes metric units (meters and kilometers). + */ + getUnitsFeetMiles(): boolean; + + /** + * Set display units to imperial (feet and miles) or metric (meters and kilometers). + * This setting affects only the values displayed in the status bar and the scale bar. + * The values passed and returned with an object's getters and setters are always metric. + */ + setUnitsFeetMiles(unitsFeetMiles: boolean): void; + + /** + * Enables or disables building selection. + * If enabled, clicking a building will pop a feature balloon containing information from the Google 3D Warehouse database. + */ + setBuildingSelectionEnabled(buildingSelectionEnabled: boolean): void; + + /** + * Whether or not building selection is enabled. + */ + getBuildingSelectionEnabled(): boolean; + + /** + * Returns true if building highlighting is enabled. + */ + getBuildingHighlightingEnabled(): boolean; + + /** + * Enables or disables building highlighting. + * When enabled, buildings will be highlighted when they are moused over. + */ + setBuildingHighlightingEnabled(buildingHighlightingEnabled: boolean): void; + + /** + * Returns the terrain exaggeration value. Valid values are in the range of 1.0 through 3.0. + */ + getTerrainExaggeration(): number; + + /** + * Set the terrain exaggeration value. Valid values are in the range of 1.0 through 3.0. + * Attempting to set outside of this range will result in the value being clamped. + */ + setTerrainExaggeration(terrainExaggeration: number): void; + + /** + * When enabled, the view will change to 'ground level view' when the camera reaches ground level. + * This view provides pan and lookAt controls, but no zoom slider. + * The tilt will be set to 90, or parallel with level ground. + */ + setAutoGroundLevelViewEnabled(autoGroundLevelViewEnabled: boolean): void; + + /** + * Whether automatic ground level view is enabled. + */ + getAutoGroundLevelViewEnabled(): boolean; + } + + /** + * Adds a node to the end of the list of children of a specified feature. + * Returns the appended object. + */ + export class GESchemaObjectContainer { + + /** + * Adds a node to the end of the list of children of a specified feature. + * Returns the appended object. + */ + appendChild(object: T): void; + + /** + * Removes a node from the list of children of a specified object. + */ + removeChild(oldChild: T): void; + + /** + * Inserts a child before the referenced child in the list of objects. + */ + insertBefore(newChild: T, refChild: T): void; + + /** + * Replaces existing child in the list of features. + * Returns the old child. + */ + replaceChild(newChild: T, oldChild: T): void; + + /** + * Returns true if the container is not empty. + */ + hasChildNodes(): boolean; + + /** + * First child in the list of objects. + */ + getFirstChild(): T; + + /** + * Last child in the list of objects. + */ + getLastChild(): T; + + /** + * List of features (for KmlContainer), or list of features, styles, and schemas (for KmlDocument). + * Returns true if there are any child nodes. + */ + getChildNodes(): KmlObjectList; + } + + /** + * A container class that holds one or more features and allows the creation of nested hierarchies. + */ + export class GEFeatureContainer extends GESchemaObjectContainer {} + + /** + * A container object that contains an array of geometries, typically the children of a multi-geometry. + */ + export class GEGeometryContainer extends GESchemaObjectContainer {} + + /** + * A container object that contains an array of closed line strings, typically the outer boundary of a Polygon. + * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. + * A Polygon can contain multiple LinearRing objects used as inner boundaries. + */ + export class GELinearRingContainer extends GESchemaObjectContainer {} + + /** + * A container that holds a collection of KmlStyle and KmlStyleMap objects. + * The KmlStyleMap object selects a style based on the current mode of the Placemark. + * An object derived from KmlStyleSelector is uniquely identified by its ID and its URL. + */ + export class GEStyleSelectorContainer extends GESchemaObjectContainer {} + + /** + * Defines the x and y coordinates of a 2D vector. + */ + export class KmlVec2 { + + /** + * Sets the coordinates of the vector. + */ + set( + x: number, + xUnits: KmlUnitsEnum, + y: number, + yUnits: KmlUnitsEnum + ): void; + + /** + * Indicates the x coordinate. + */ + getX(): number; + + /** + * Indicates the x coordinate. + */ + setX(x: number): void; + + /** + * Indicates the y coordinate. + */ + getY(): number; + + /** + * Indicates the y coordinate. + */ + setY(y: number): void; + + /** + * Units in which the x value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIXELS + * * GEPlugin.UNITS_INSET_PIXELS + */ + getXUnits(): KmlUnitsEnum; + + /** + * Units in which the x value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIXELS + * * GEPlugin.UNITS_INSET_PIXELS + */ + setXUnits(xUnits: KmlUnitsEnum): void; + + /** + * Units in which the y value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIyELS + * * GEPlugin.UNITS_INSET_PIyELS + */ + getYUnits(): KmlUnitsEnum; + + /** + * Units in which the y value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIyELS + * * GEPlugin.UNITS_INSET_PIyELS + */ + setYUnits(xUnits: KmlUnitsEnum): void; + } + + /** + * The GESun class controls the dawn to dusk views. + */ + export class GESun { + + /** + * Specifies whether the feature is drawn in the 3D viewer when it is initially loaded. + * In order for a feature to be visible, the visibility property and all of its ancestors must also be set to 1. + */ + getVisibility(): boolean; + + /** + * Specifies whether the feature is drawn in the 3D viewer when it is initially loaded. + * In order for a feature to be visible, the visibility property and all of its ancestors must also be set to 1. + */ + setVisibility(visibility: boolean): void; + } + + /** + * The KmlColor object values are expressed in hexadecimal notation. + * The range of values for any one color component is 0 to 255 (00 to ff). + * For alpha, 00 is fully transparent and ff is fully opaque. + * The order of expression is aabbggrr, where aa=alpha (00 to ff); bb=blue (00 to ff); gg=green (00 to ff); rr=red (00 to ff). + * For example, if you want to apply a blue color with 50 percent opacity to an overlay, + * you would specify the following when setting color value: 7fff0000, where alpha=0x7f, blue=0xff, green=0x00, and red=0x00. + */ + export class KmlColor { + + /** + * Set the color of an object. + */ + set(color: string): void; + + /** + * Returns the color of an object. + */ + get(): string; + + /** + * red numerical value + */ + getR(): number; + + /** + * red numerical value + */ + setR(r: number): void; + + /** + * green numerical value + */ + getG(): number; + + /** + * green numerical value + */ + setG(g: number): void; + + /** + * blue numerical value + */ + getB(): number; + + /** + * blue numerical value + */ + setB(b: number): void; + + /** + * opacity value + */ + getA(): number; + + /** + * opacity value + */ + setA(a: number): void; + } + + /** + * The event object used with all KMLObjects. + * For more information about events, see the Document Object Model Events specification at http: + */ + export class KmlEvent { + + /** + * Cancels the default action of the event. + * For example, calling this method in a placemark click handler prevents the placemark's default balloon from popping up. + */ + preventDefault(): void; + + /** + * Prevents event propagation. + * For example, if click event handlers are set up on both the GEGlobe and GEWindow objects, + * and stopPropagation is called in the GEGlobe click event handler, the GEWindow event handler will not be triggered when the globe is clicked. + */ + stopPropagation(): void; + + /** + * The object to which the KMLEvent was originally dispatched. + */ + getTarget(): GEEventEmitter; + + /** + * The target whose event listeners are currently being processed. + */ + getCurrentTarget: GEEventEmitter; + + /** + * The current stage of the flow of events. + */ + getEventPhase(): GEEventPhaseEnum; + + /** + * Indicates whether or not an event is a bubbling event. + */ + getBubbles(): boolean; + + /** + * Indicates whether the event can be cancelled. + * + * Note: Currently, cancelable has no effect. + */ + getCancelable(): boolean; + } + + /** + * Represents a mouse input event. + */ + export class KmlMouseEvent extends KmlEvent { + + /** + * The button on the mouse was pressed. + * Possible values include 0, 1, 2, where 0 is left, 1 is middle, and 2 is right mouse key. + */ + getButton(): number; + + /** + * The x coordinate at which the event occurred, measured in pixels from the left edge of the plug-in window. + */ + getClientX(): number; + + /** + * The y coordinate at which the event occurred, measured in pixels from the top edge of the plug-in window. + */ + getClientY(): number; + + /** + * The x coordinate at which the event occurred, measured in pixels from the left edge of the computer screen. + */ + getScreenX(): number; + + /** + * The y coordinate at which the event occurred, measured in pixels from the top edge of the computer screen. + */ + getScreenY(): number; + + /** + * The latitude at which the event occurred, in decimal degrees. + */ + getLatitude(): number; + + /** + * The longitude at which the event occurred, in decimal degrees. + */ + getLongitude(): number; + + /** + * The altitude at which the event occurred, in meters. + */ + getAltitude(): number; + + /** + * Indicates whether a mouse action occurred while on the Google Earth globe. + */ + getDidHitGlobe(): boolean; + + /** + * Indicates whether the ALT key was held down when an event occurred. + */ + getAltKey(): boolean; + + /** + * Indicates whether the CTRL key was held down when an event occurred. + */ + getCtrlKey(): boolean; + + /** + * Indicates whether the SHIFT key was held down when an event occurred. + */ + getShiftKey(): boolean; + + /** + * Used with the mouseover and mouseout events to specify a secondary target. + * For mouseover, it specifies the object that the mouse was over. + * For mouseout, it specifies the new object that the mouse is over. + */ + getRelatedTarget(): GEEventEmitter; + + /** + * Returns the timestamp of the event, in Unix time. + */ + getTimeStamp(): number; + } + + /** + * Defines when and how an event gets passed in and triggered from the Google Earth Plug-in. + */ + export class GEEventEmitter { + + /** + * Triggers an event when the user clicks a location in Google Earth with the mouse. + */ + click(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user double clicks a location in Google Earth with the mouse. + */ + dblclick(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user moves the mouse pointer over a location in Google Earth. + */ + mouseover(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user presses the mouse button over a location in Google Earth. + */ + mousedown(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user releases the mouse button over a location in Google Earth. + */ + mouseup(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user moves the mouse off of the object in Google Earth. + */ + mouseout(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user moves the mouse inside Google Earth. + */ + mousemove(event: KmlMouseEvent): void; + } + + /** + * The base class for all the other objects in the Google Earth Plug-in. + * The methods and behavior of KMLObject are inherited by all other objects. + * This is an abstract base class and cannot be used directly. + * It provides the id attribute, which allows unique identification of an object. + */ + export class KmlObject extends GEEventEmitter { + + /** + * The interface name (i.e. 'KmlPlacemark') of the object. + */ + getType(): string; + + /** + * Test whether this object is the same as another object. + * Useful for Chrome and Safari, where the comparison a==b sometimes fails for plugin objects. + */ + equals(compareTo: KmlObject): boolean; + + /** + * The unique ID of the KML object. + */ + getId(): string; + + /** + * The unique URL of the KML object. + * This is the base address joined with the ID using the # character. + * + * For example: http://www.google.com/bar.kml#atlantis + */ + getUrl(): string; + + /** + * The parent node of the KML object. + */ + getParentNode(): KmlObject; + + /** + * The document that owns the KML object. + */ + getOwnerDocument(): KmlDocument; + + /** + * Permanently deletes an object, allowing its ID to be reused. + * Attempting to access the object once it is released will result in an error. + */ + release(): void; + } + + /** + * A collection of KmlObjects. + */ + export class KmlObjectList { + + /** + * Gets an item from the object list. For example, list.item(0) returns the first object in the list. + */ + item(index: number): T; + + /** + * Number of objects in collection. + */ + getLength(): number; + } + + /** + * The base class for KmlStyle and KmlStyleMap. + */ + export class KmlStyleSelector extends KmlObject {} + + /** + * Defines the icon, label, line, list, polygon, and balloon styles. + */ + export class KmlStyle extends KmlStyleSelector { + + /** + * Specifies how icons for point placemarks are drawn in Google Earth. + */ + getIconStyle(): KmlIconStyle; + + /** + * Specifies how the name of a feature is drawn in the 3D viewer. + * A custom color, color mode, and scale for the label (name) can be specified. + */ + getLabelStyle(): KmlLabelStyle; + + /** + * Specifies the drawing style (color, color mode, and line width) for line geometry. + * Line geometry includes the outlines of outlined polygons and the extruded tether of Placemark icons (if extrusion is enabled). + */ + getLineStyle(): KmlLineStyle; + + /** + * Specifies the style for list geometry. + */ + getListStyle(): KmlListStyle; + + /** + * Specifies the drawing style for polygons, including polygon extrusions (which look like the walls of buildings) and line extrusions (which look like solid fences). + */ + getPolyStyle(): KmlPolyStyle; + + /** + * Specifies the drawing style for balloons. + */ + getBalloonStyle(): KmlBalloonStyle; + } + + /** + * The KmlColorStyle object is an abstract object. + * It specifies the color and color mode of extended style types. + */ + export class KmlColorStyle extends KmlObject { + + /** + * Color and opacity (alpha) values. + */ + getColor(): KmlColor; + + /** + * Specifies which color mode effect to apply to the base color. + * + * See also: + * + * * GEPlugin.COLOR_NORMAL + * * GEPlugin.COLOR_INHERIT + * * GEPlugin.COLOR_RANDOM + */ + getColorMode(): KmlColorModeEnum; + + /** + * Specifies which color mode effect to apply to the base color. + * + * See also: + * + * * GEPlugin.COLOR_NORMAL + * * GEPlugin.COLOR_INHERIT + * * GEPlugin.COLOR_RANDOM + */ + setColorMode(colorMode: KmlColorModeEnum): void; + } + + /** + * Specifies how icons for point placemarks are drawn in Google Earth. + * The icon property specifies the icon image. + * The scale property specifies the x, y scaling of the icon. + * The color specified in the color property of KmlIconStyle is blended with the color of the Icon. + */ + export class KmlIconStyle extends KmlColorStyle { + + /** + * Resizes the icon. + */ + getScale(): number; + + /** + * Resizes the icon. + */ + setScale(scale: number): void; + + /** + * The direction that icons are set to point, clockwise, and in degrees. + */ + getHeading(): number; + + /** + * The direction that icons are set to point, clockwise, and in degrees. + */ + setHeading(): number; + + /** + * A custom Icon. In KmlIconStyle, the only child element of KmlIcon is href and href is an HTTP address or a local file specification used to load an icon. + */ + getIcon(): KmlIcon; + + /** + * A custom Icon. In KmlIconStyle, the only child element of KmlIcon is href and href is an HTTP address or a local file specification used to load an icon. + */ + setIcon(icon: KmlIcon): void; + + /** + * Specifies the position within the Icon that is anchored to the point specified in the placemark. + * The x and y values can be specified in three different ways: as pixels, as fractions of the icon, or as inset pixels, which is an offset in pixels from the upper right corner of the icon. + * The x and y positions can be specified in different ways. + * For example, x can be in pixels and y can be a fraction. + * The origin of the coordinate system is in the lower left corner of the icon. + */ + getHotSpot(): KmlVec2; + } + + /** + * Specifies how the name of a feature is drawn in the 3D viewer. + * A custom color, color mode, and scale for the label (name) can be specified. + */ + export class KmlLabelStyle extends KmlColorStyle { + + /** + * Resizes the label. + */ + getScale(): number; + + /** + * Resizes the label. + */ + setScale(scale: number): void; + } + + /** + * The KmlLineStyle object specifies the drawing style (color, color mode, and line width) for all line geometry. + * Line geometry includes the outlines of outlined polygons and the extruded "tether" of Placemark icons (if extrusion is enabled). + */ + export class KmlLineStyle extends KmlColorStyle { + + /** + * Width of the line, in pixels. + */ + getWidth(): number; + + /** + * Width of the line, in pixels. + */ + setWidth(width: number): void; + } + + /** + * Specifies the drawing style for all polygons, including polygon extrusions (which look like the walls of buildings) and line extrusions (which look like solid fences). + */ + export class KmlPolyStyle extends KmlColorStyle { + + /** + * Specifies whether or not to fill the polygon. Possible values 1 (fill) and 0 (no fill). + */ + getFill(): boolean; + + /** + * Specifies whether or not to fill the polygon. Possible values 1 (fill) and 0 (no fill). + */ + setFill(fill: boolean): void; + + /** + * Specifies whether to outline the polygon. Polygon outlines use the current KmlLineStyle. + */ + getOutline(): boolean; + + /** + * Specifies whether to outline the polygon. Polygon outlines use the current KmlLineStyle. + */ + setOutline(outline: boolean): void; + } + + /** + * Specifies how a feature is displayed in the list view. + */ + export class KmlListStyle extends KmlObject { + + /** + * Background color for the Snippet. + */ + getBgColor(): KmlColor; + + /** + * Maximum number of lines of text for the Snippet. + */ + getMaxSnippetLines(): number; + + /** + * Maximum number of lines of text for the Snippet. + */ + setMaxSnippetLines(maxSnippetLines: number): void; + + /** + * Specifies how a feature should be displayed in a list view. + */ + getListItemType(): KmlListItemTypeEnum; + } + + /** + * Specifies how the description balloon for placemarks is drawn. + */ + export class KmlBalloonStyle extends KmlObject { + + /** + * Background color of the balloon (optional). + */ + getBgColor(): KmlColor; + + /** + * Foreground color for text. The default is black (ff000000). + */ + getTextColor(): KmlColor; + + /** + * The text contained in the balloon. + */ + getText(): string; + + /** + * The text contained in the balloon. + */ + setText(text: string): void; + } + + /** + * Specifies the top, bottom, right, and left sides of a bounding box on the Earth's surface. + */ + export class KmlLatLonBox extends KmlObject { + + /** + * Sets the north, south, east, and west edges of the bounding box, as well as the rotation of the overlay. + */ + setBox( + north: number, + south: number, + east: number, + west: number, + rotation: number + ): void; + + /** + * Specifies the latitude of the north edge of the bounding box, in decimal degrees from -90 to 90. + */ + getNorth(): number; + + /** + * Specifies the latitude of the north edge of the bounding box, in decimal degrees from -90 to 90. + */ + setNorth(north: number): void; + + /** + * Specifies the latitude of the south edge of the bounding box, in decimal degrees from -90 to 90. + */ + getSouth(): number; + + /** + * Specifies the latitude of the south edge of the bounding box, in decimal degrees from -90 to 90. + */ + setSouth(south: number): void; + + /** + * Specifies the longitude of the east edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + getEast(): number; + + /** + * Specifies the longitude of the east edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + setEast(east: number): void; + + /** + * Specifies the longitude of the west edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + getWest(): number; + + /** + * Specifies the longitude of the west edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + setWest(west: number): void; + + /** + * Specifies a rotation of the overlay about its center, in degrees. + * Values can be +/-180. The default is 0 (north). + * Rotations are specified in a counterclockwise direction. + */ + getRotation(): number; + + /** + * Specifies a rotation of the overlay about its center, in degrees. + * Values can be +/-180. The default is 0 (north). + * Rotations are specified in a counterclockwise direction. + */ + setRotation(rotation: number): void; + } + + /** + * Specifies a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + export class KmlLatLonAltBox extends KmlLatLonBox { + + /** + * Sets the north, south, east, west, rotation, minAltitude, maxAltitude, and altitudeMode of bounding box. + */ + setAltBox( + north: number, + south: number, + east: number, + west: number, + rotation: number, + minAltitude: number, + maxAltitude: number, + altitudeMode: KmlAltitudeModeEnum + ): void; + + /** + * Minimum altitude, specified in meters above sea level. + */ + getMinAltitude(): number; + + /** + * Minimum altitude, specified in meters above sea level. + */ + setMinAltitude(minAltitude: number): void; + + /** + * Maximim altitude, specified in meters above sea level. + */ + getMaxAltitude(): number; + + /** + * Maximim altitude, specified in meters above sea level. + */ + setMaxAltitude(maxAltitude: number): void; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): number; + } + + /** + * The KmlLod or level of detail, describes the size of the projected region on the screen that is required in order for the region to be considered active. + * Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + export class KmlLod extends KmlObject { + + /** + * Sets the minLodPixels, maxLodPixels, minFadeExtent, and maxFadeExtent for the projected region on the screen. + */ + set( + minLodPixels: number, + maxLodPixels: number, + minFadeExtent: number, + maxFadeExtent: number + ): void; + + /** + * Specifies measurement in screen pixels that represents the minimum limit of the visibility range for a given Region. + * Google Earth calculates the size of the region when projected onto screen space. + * Then it computes the square root of the region's area (if, for example, the Region is square and the viewpoint is directly above the Region, and the Region is not tilted, this measurement is equal to the width of the projected Region). + * If this measurement falls within the limits defined by minLodPixels and maxLodPixels (and if the LatLonAltBox is in view), the region is active. + * If this limit is not reached, the associated geometry is considered to be too far from the user's viewpoint to be drawn. + */ + getMinLodPixels(): number; + + /** + * Specifies measurement in screen pixels that represents the minimum limit of the visibility range for a given Region. + * Google Earth calculates the size of the region when projected onto screen space. + * Then it computes the square root of the region's area (if, for example, the Region is square and the viewpoint is directly above the Region, and the Region is not tilted, this measurement is equal to the width of the projected Region). + * If this measurement falls within the limits defined by minLodPixels and maxLodPixels (and if the LatLonAltBox is in view), the region is active. + * If this limit is not reached, the associated geometry is considered to be too far from the user's viewpoint to be drawn. + */ + setMinLodPixels(minLodPixels: number): void; + + /** + * Measurement in screen pixels that represents the maximum limit of the visibility range for a given Region. + * A value of -1, the default, indicates "active to infinite size." + */ + getMaxLodPixels(): number; + + /** + * Measurement in screen pixels that represents the maximum limit of the visibility range for a given Region. + * A value of -1, the default, indicates "active to infinite size." + */ + setMaxLodPixels(maxLogPixels: number): void; + + /** + * Distance over which the geometry fades, from fully opaque to fully transparent. + * This ramp value, expressed in screen pixels, is applied at the minimum end of the LOD (visibility) limits. + */ + getMinFadeExtent(): number; + + /** + * Distance over which the geometry fades, from fully opaque to fully transparent. + * This ramp value, expressed in screen pixels, is applied at the minimum end of the LOD (visibility) limits. + */ + setMinFadeExtent(minFadeExtent: number): void; + + /** + * Distance over which the geometry fades, from fully transparent to fully opaque. + * This ramp value, expressed in screen pixels, is applied at the maximum end of the LOD (visibility) limits. + */ + getMaxFadeExtent(): number; + + /** + * Distance over which the geometry fades, from fully transparent to fully opaque. + * This ramp value, expressed in screen pixels, is applied at the maximum end of the LOD (visibility) limits. + */ + setMaxFadeExtent(maxFadeExtent: number): void; + } + + /** + * The KmlRegion object is used to set region objects and their properties. + * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. + * In addition, a Region contains an LOD (level of detail) extent that defines a validity range of the associated Region in terms of projected screen size. + * A Region is said to be "active" when the bounding box is within the user's view and the LOD requirements are met. + * Objects associated with a Region are drawn only when the Region is active. + * When the viewRefreshMode is onRegion, the Link or Icon is loaded only when the Region is active. + */ + export class KmlRegion extends KmlObject { + + /** + * Sets the latLonAltBox and lod for the region. + */ + set(latLonAltBox: KmlLatLonAltBox, lod: KmlLod): void; + + /** + * A bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + getLatLonAltBox(): KmlLatLonAltBox; + + /** + * A bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + setLatLonAltBox(latLonAltBox: KmlLatLonAltBox): void; + + /** + * LOD is an abbreviation for Level of Detail. + * Lod describes the size of the projected region on the screen that is required in order for the region to be considered "active. + * " Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + getLod(): KmlLod; + + /** + * LOD is an abbreviation for Level of Detail. + * Lod describes the size of the projected region on the screen that is required in order for the region to be considered "active. + * " Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + setLod(lod: KmlLod): void; + } + + /** + * Represents a specific point in time. + * The plugin accepts time in this format only; it does not accept JavaScript date or time objects. + */ + export class KmlDateTime { + + /** + * Set the date. Accepts only XML Schema time (see XML Schema Part 2: Datatypes Second Edition). + * The value can be expressed as yyyy-mm-ddThh:mm:sszzzzzz, where T is the separator between the date and the time, + * and the time zone is either Z(for UTC) or zzzzzz, which represents +/-hh:mm in relation to UTC. + * Additionally, the value can be expressed as a date only. + */ + set(date: string): void; + + /** + * Returns the date and time in XML Schema time format. + */ + get(): string; + } + + /** + * An abstract object and cannot be used directly in a JavaScript file. + * This element is extended by the TimeSpan and TimeStamp objects. + */ + export class KmlTimePrimitive extends KmlObject {} + + /** + * Represents a single moment in time. + * This is a simple element and contains no children. + * Its value is a dateTime, specified in XML time. + * The precision of the TimeStamp is dictated by the dateTime value in the when property. + */ + export class KmlTimeStamp extends KmlTimePrimitive { + + /** + * Represents a single moment in time. + * This is a simple element and contains no children. + * Its value is a dateTime, specified in XML time. + * The precision of the TimeStamp is dictated by the dateTime value in the when property. + * + * * dateTime gives second resolution + * * date gives day resolution + * * gYearMonth gives month resolution + * * gYear gives year resolution + */ + getWhen(): KmlDateTime; + } + + /** + * Represents an extent in time bounded by begin and end dateTimes. + */ + export class KmlTimeSpan extends KmlTimePrimitive { + + /** + * Describes the beginning instant of a time period. + * If absent, the beginning of the period is unbounded. + */ + getBegin(): KmlDateTime; + + /** + * Describes the ending instant of a time period. + * If absent, the end of the period is unbounded. + */ + getEnd(): KmlDateTime; + } + + /** + * This is an abstract class and cannot be created directly. + * This class is extended by KmlCamera and KmlLookAt. + */ + export class KmlAbstractView extends KmlObject { + + /** + * Creates a new KmlLookAt object that matches as closely as possible this KmlAbstractView. + * KmlLookAt is unable to represent roll, so roll values in the current view will not be passed to the new KmlLookAt object. + * + * If this view is already a KmlLookAt, this function returns a new KmlLookAt representing the same view. + */ + copyAsLookAt(): KmlLookAt; + + /** + * Creates a new KmlCamera object that matches this KmlAbstractView. + * + * If this view is already a KmlCamera, this function returns a new KmlCamera representing the same view. + */ + copyAsCamera(): KmlCamera; + + /** + * Returns the KmlTimeStamp or KmlTimeSpan object associated with this view. + */ + getTimePrimitive(): KmlTimePrimitive; + + /** + * Associate a KmlTimeStamp or KmlTimeSpan object with this view. + */ + setTimePrimitive(timePrimitive: KmlTimePrimitive): void; + + /** + * Returns the viewer options on the current view. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + */ + getViewerOptions(): KmlViewerOptions; + + /** + * Sets the viewer options on the current view. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + */ + setViewerOptions(viewerOptions: KmlViewerOptions): void; + } + + /** + * Defines a camera that is associated with anything derived from feature. + * The LookAt element positions the "camera" in relation to the object that is being viewed. + * This class either positions the relative to a feature, or you can manually change the view, using ge.getView().setAbstractView(). + */ + export class KmlLookAt extends KmlAbstractView { + + /** + * Sets the latitude, longitude, altitude, altitudeMode, heading, tilt, and range for the camera. + */ + set ( + latitude: number, + longitude: number, + altitude: number, + altitudeMode: KmlAltitudeModeEnum, + heading: number, + tilt: number, + range: number + ): void; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLatitude(): number; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLatitude(latitude: number): void; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLongitude(): number; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLongitude(longitude: number): void; + + /** + * The distance in meters from the point specified by longitude, latitude, and altitude for the LookAt position. + */ + getRange(): number; + + /** + * The distance in meters from the point specified by longitude, latitude, and altitude for the LookAt position. + */ + setRange(range: number): void; + + /** + * Angle between the direction of the LookAt position and the normal to the surface of the earth. + * Values range from 0 to 90 degrees. Values for tilt cannot be negative. + * A tilt value of 0 degrees indicates viewing from directly above. + * A tilt value of 90 degrees indicates viewing along the horizon. + */ + getTilt(): number; + + /** + * Angle between the direction of the LookAt position and the normal to the surface of the earth. + * Values range from 0 to 90 degrees. Values for tilt cannot be negative. + * A tilt value of 0 degrees indicates viewing from directly above. + * A tilt value of 90 degrees indicates viewing along the horizon. + */ + setTilt(tilt: number): void; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + getHeading(): number; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + setHeading(heading: number): void; + + /** + * Distance from the earth's surface, in meters. + */ + getAltitude(): number; + + /** + * Distance from the earth's surface, in meters. + */ + setAltitude(altitude: number): void; + + /** + * Specifies how altitude components in the coordinates element are interpreted. + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how altitude components in the coordinates element are interpreted. + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + } + + /** + * Defines the camera that views the scene. + * This element defines the position of the camera relative to the Earth's surface as well as the viewing direction of the camera. + * The camera position is defined by longitude, latitude, altitude, and altitudeMode. + * The viewing direction of the camera is defined by heading, tilt, and roll. + * Camera can be a child element of any feature. + */ + export class KmlCamera extends KmlAbstractView { + + /** + * Sets the latitude, longitude, altitude, alitudeMode, heading, tilt, and roll values. + */ + set( + latitude: number, + longitude: number, + altitude: number, + altitudeMode: KmlAltitudeModeEnum, + heading: number, + tilt: number, + roll: number + ): void; + + /** + * Latitude of the camera location. Degrees north or south of the Equator (0 degrees). Values range from -90 degrees to 90 degrees. + */ + getLatitude(): number; + + /** + * Latitude of the camera location. Degrees north or south of the Equator (0 degrees). Values range from -90 degrees to 90 degrees. + */ + setLatitude(latitude: number): void; + + /** + * Longitude of the camera location. Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + getLongitude(): number; + + /** + * Longitude of the camera location. Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + setLongitude(longitude: number): void; + + /** + * Distance from the earth's surface. + */ + getAltitude(): number; + + /** + * Distance from the earth's surface. + */ + setAltitude(altitude: number): void; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + getHeading(): number; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + setHeading(heading: number): void; + + /** + * Angle between the direction of the camera position and the normal to the surface of the earth. Values range from 0 to 360 degrees. + * A tilt value of 0 degrees indicates viewing from directly above, 90 degrees indicates viewing along the horizon, and 180 degrees indicates viewing straight up at the sky. + */ + getTilt(): number; + + /** + * Angle between the direction of the camera position and the normal to the surface of the earth. Values range from 0 to 360 degrees. + * A tilt value of 0 degrees indicates viewing from directly above, 90 degrees indicates viewing along the horizon, and 180 degrees indicates viewing straight up at the sky. + */ + setTilt(tilt: number): void; + + /** + * Rotation, in degrees, of the camera around the Z axis. Values range from -180 to +180 degrees. + */ + getRoll(): number; + + /** + * Rotation, in degrees, of the camera around the Z axis. Values range from -180 to +180 degrees. + */ + setRoll(roll: number): void; + + /** + * Specifies how altitude components in the coordinates are interpreted. + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how altitude components in the coordinates are interpreted. + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + } + + /** + * The KmlGeometry object is an abstract object and cannot be used directly. + * It provides a placeholder object for all derived Geometry objects. + */ + export class KmlGeometry extends KmlObject {} + + /** + * Specifies an AltitudeMode for derived classes. + */ + export class KmlAltitudeGeometry extends KmlGeometry { + + /** + * Specifies how altitude components in the geometry coordinates are interpreted. + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how altitude components in the geometry coordinates are interpreted. + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + } + + /** + * A 3D object described in a referenced COLLADA file. + * COLLADA files have a .dae file extension. + * Models are created in their own coordinate space and then located, positioned, and scaled in Google Earth. + * Google Earth supports the COLLADA common profile, with the following exceptions: + * + * * Google Earth supports only triangles and lines as primitive types. The maximum number of triangles allowed is 21845. + * * Google Earth does not support animation or skinning. + * * Google Earth does not support external geometry references. + */ + export class KmlModel extends KmlAltitudeGeometry { + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + getLocation(): KmlLocation; + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + setLocation(location: KmlLocation): void; + + /** + * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + getOrientation(): KmlOrientation; + + /** + * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + setOrientation(orientation: KmlOrientation): void; + + /** + * Scales a model along the x, y, and z axes in the model's coordinate space + */ + getScale(): KmlScale; + + /** + * Scales a model along the x, y, and z axes in the model's coordinate space + */ + setScale(scale: KmlScale): void; + + /** + * Returns the link of the collada model. + */ + getLink(): KmlLink; + + /** + * Sets the link of the collada model. + */ + setLink(link: KmlLink): void; + } + + /** + * A container for zero or more geometry primitives associated with the same feature. + */ + export class KmlMultiGeometry extends KmlGeometry { + + /** + * The collection of geometries that are children of this multi-geometry. + */ + getGeometries(): GEGeometryContainer; + } + + /** + * Specifies the behavior of the object's geometry. + */ + export class KmlExtrudableGeometry extends KmlAltitudeGeometry { + + /** + * Specifies whether to connect the geometry to the ground. + */ + getExtrude(): boolean; + + /** + * Specifies whether to connect the geometry to the ground. + */ + setExtrude(extrude: boolean): void; + + /** + * Specifies whether to allow the geometry to follow the terrain elevation. + */ + getTessellate(): boolean; + + /** + * Specifies whether to allow the geometry to follow the terrain elevation. + */ + setTessellate(tessellate: boolean): void; + } + + /** + * A Polygon is defined by an outer boundary and 0 or more inner boundaries. + * The boundaries, in turn, are defined by LinearRings. + * When a Polygon is extruded, its boundaries are connected to the ground to form additional polygons, which gives the appearance of a building or a box. + * Extruded Polygons use PolyStyle for their color, color mode, and fill. + */ + export class KmlPolygon extends KmlExtrudableGeometry { + + /** + * Contains a LinearRing element. + */ + getOuterBoundary(): KmlLinearRing; + + /** + * Contains a LinearRing element. + */ + setOuterBoundary(outerBoundary: KmlLinearRing): void; + + /** + * Contains a LinearRing element. + * You can specify multiple innerBoundary properties, which create multiple cut-outs inside the Polygon. + */ + getInnerBoundaries(): GELinearRingContainer; + } + + /** + * A geographic location defined by longitude, latitude, and (optional) altitude. + * When a Point is contained by a Placemark, the point itself determines the position of the Placemark's name and icon. + * When a Point is extruded, it is connected to the ground with a line. This tether uses the current LineStyle. + */ + export class KmlPoint extends KmlExtrudableGeometry { + + /** + * Sets altitudeMode, extrude, tessellate, latitude, longitude, and altitude values. + */ + set( + latitude: number, + longitude: number, + altitude: number, + altitudeMode: KmlAltitudeModeEnum, + extrude: boolean, + tessellate: boolean + ): void; + + /** + * Sets the latitude and longitude. + */ + setLatLng(latitude: number, longitude: number): void; + + /** + * The point's latitude, in degrees. + */ + getLatitude(): number; + + /** + * The point's latitude, in degrees. + */ + setLatitude(latitude: number): void; + + /** + * The point's longitude, in degrees. + */ + getLongitude(): number; + + /** + * The point's longitude, in degrees. + */ + setLongitude(longitude: number): void; + + /** + * The point's altitude, in meters. + */ + getAltitude(): number; + + /** + * The point's altitude, in meters. + */ + setAltitude(altitude: number): void; + } + + /** + * Defines a connected set of line segments. + * Use KmlLineStyle to specify the color, color mode, and width of the line. + * When a LineString is extruded, the line is extended to the ground, forming a polygon that looks somewhat like a wall or fence. + * For extruded LineStrings, the line itself uses the current LineStyle, and the extrusion uses the current PolyStyle. + */ + export class KmlLineString extends KmlExtrudableGeometry { + + /** + * Two or more coordinate tuples, each consisting of floating point values for longitude, latitude, and altitude. + * The altitude component is optional. + */ + getCoordinates(): KmlCoordArray; + + /** + * Added to the altitude values for all points on the line string. + * Adjusts the altitude of the feature as a whole, without the need to update each coordinate set. + */ + setAltitudeOffset(altitudeOffset: number): void; + + /** + * Returns the altitudeOffset, or 0 if not set. + */ + getAltitudeOffset(): number; + } + + /** + * Defines a closed line string, typically the outer boundary of a Polygon. + * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. + * A Polygon can contain multiple LinearRing elements used as inner boundaries. + * You do not need to connect the first and last points. + */ + export class KmlLinearRing extends KmlLineString {} + + + /** + * The KmlFeature object is an abstract object and is the base for all feature types (for example Placemarks, Overlays, and NetworkLinks). + */ + export class KmlFeature extends KmlObject { + + /** + * Retrieves the contents of the feature's element. + * The retrieved contents are scrubbed to remove JavaScript; CSS; and iframe, embed, and object tags. + * + * It should be safe to insert the resulting HTML into your page without concern for malicious content embedded in the feature data; + * however any feature depending on CSS or Javascript will not work. + */ + getBalloonHtml(): string; + + /** + * Retrieves the contents of the feature's element. The contents are not scrubbed. + * Use this method only if you trust the source of the feature data. + */ + getBalloonHtmlUnsafe(): string; + + /** + * User-defined text displayed in the plugin as the label for the object (for example, for a Placemark). + */ + getName(): string; + + /** + * User-defined text displayed in the plugin as the label for the object (for example, for a Placemark). + */ + setName(name: string): void; + + /** + * Specifies whether the feature is drawn in the plugin. + * In order for a feature to be visible, the visibility of all its ancestors must also be set to true. + * In the Google Earth List View, each feature has a checkbox that allows the user to control visibility of the feature. + */ + getVisibility(): boolean; + + /** + * Specifies whether the feature is drawn in the plugin. + * In order for a feature to be visible, the visibility of all its ancestors must also be set to true. + * In the Google Earth List View, each feature has a checkbox that allows the user to control visibility of the feature. + */ + setVisibility(visibility: boolean): void; + + /** + * Default state of left panel. + */ + getOpen(): boolean; + + /** + * Default state of left panel. + */ + setOpen(open: boolean): void; + + /** + * Specifies a value representing an unstructured address written as a standard street, city, state address, and/or as a postal code. + */ + getAddress(): string; + + /** + * Specifies a value representing an unstructured address written as a standard street, city, state address, and/or as a postal code. + */ + setAddress(address: string): void; + + /** + * Specifies a short description of the feature. + */ + getSnippet(): string; + + /** + * Specifies a short description of the feature. + */ + setSnippet(snippet: string): void; + + /** + * User-supplied text that appears in the description balloon. + */ + getDescription(): string; + + /** + * User-supplied text that appears in the description balloon. + */ + setDescription(description: string): void; + + /** + * Stores either the lookAt or camera view. + */ + getAbstractView(): KmlAbstractView; + + /** + * Stores either the lookAt or camera view. + */ + setAbstractView(abstractView: KmlAbstractView): void; + + /** + * URI of a Style or StyleMap defined in a Document. + * It refers to a Plug-in intitiated object. + */ + getStyleUrl(): string; + + /** + * URI of a Style or StyleMap defined in a Document. + * It refers to a Plug-in intitiated object. + */ + setStyleUrl(styleUrl: string): void; + + /** + * The style based on the current mode of the Placemark. + */ + getStyleSelector(): KmlStyleSelector; + + /** + * The style based on the current mode of the Placemark. + */ + setStyleSelector(styleSelector: KmlStyleSelector): void; + + /** + * Specifies region objects and their properties. + * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. + */ + getRegion(): KmlRegion; + + /** + * Specifies region objects and their properties. + * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. + */ + setRegion(region: KmlRegion): void; + + /** + * Returns the KML for a feature. + */ + getKml(): string; + + /** + * Returns previous sibling node within the container. + */ + getPreviousSibling(): KmlFeature; + + /** + * Returns the next sibling node within the container. + */ + getNextSibling(): KmlFeature; + + /** + * Returns the KmlTimeStamp or KmlTimeSpan object associated with this feature. + */ + getTimePrimitive(): KmlTimePrimitive; + + /** + * Attach a KmlTimeStamp or KmlTimeSpan object to this feature. + */ + setTimePrimitive(timePrimitive: KmlTimePrimitive): void; + + /** + * Returns the computed style of a feature, merging any inline styles with styles imported from setHref() or a StyleUrl. + * + * Note: Modifying the returned KmlStyle object is undefined and not recommended. + */ + getComputedStyle(): KmlStyle; + + /** + * Experimental Feature — this is an experimental feature and can change (or even be removed) at any time. + * The opacity of a feature, ranging from 0 (completely transparent) to 1 (complete opaque). + * The opacity of a folder or document will influence the opacity of child features. + * Thus, if a folder has an opacity of 0.5 and a child ground overlay in the folder also has an opacity of 0.5, the overlay will be drawn with an opacity of 0.25. + */ + getOpacity(): number; + + /** + * Experimental Feature — this is an experimental feature and can change (or even be removed) at any time. + * The opacity of a feature, ranging from 0 (completely transparent) to 1 (complete opaque). + * The opacity of a folder or document will influence the opacity of child features. + * Thus, if a folder has an opacity of 0.5 and a child ground overlay in the folder also has an opacity of 0.5, the overlay will be drawn with an opacity of 0.25. + */ + setOpacity(opacity: number): void; + } + + /** + * An abstract object and cannot be used directly. + * A KmlContainer object holds one or more features and allows the creation of nested hierarchies. + */ + export class KmlContainer extends KmlFeature { + + /** + * Get an element by ID. + * This is functionally equivalent to getElementByUrl with an unspecified base URL. + * + * For example: getElementByUrl('#foo'). + * + * Usage is when finding objects created with JavaScript, which have unspecified base URLs. + * The object must be a descendant of the container before it can be found. + */ + getElementById(id: string): KmlObject; + + /** + * Get an element by URL. A URL consists of the base address and ID, joined with the # character. + * + * For example: http://www.google.com/bar.kml#here_be_monsters + * + * This applies to objects that are fetched. + * In the case of plugin created objects, the URL is simply #foo. + * The object must be a descendant of the container before it can be found. + */ + getElementByUrl(url: string): KmlObject; + + /** + * Get an element by type. + */ + getElementsByType(type: string): KmlObjectList; + + /** + * A collection of features, such as name, description, and so on. + */ + getFeatures(): GEFeatureContainer; + } + + /** + * A Folder is used to arrange other features hierarchically (Folders, Placemarks, NetworkLinks, or Overlays). + * A feature is visible only if it and all of its ancestors are visible. + */ + export class KmlFolder extends KmlContainer {} + + /** + * A layer displayed in Google Earth. + */ + export class KmlLayer extends KmlFolder {} + + /** + * A container for the various layers displayed with the Google Earth Plug-in. + * It contains the same layers as Google Earth. + */ + export class KmlLayerRoot extends KmlFolder { + + /** + * Returns the layer based on the layer's ID. + */ + getLayerById(id: string): KmlLayer; + + /** + * Enables a layer based on its ID. + */ + enableLayerById(id: string, visibility: boolean): void; + + /** + * Returns the drawing order for this database. + */ + getDrawOrder(): number; + + /** + * Defines the drawing order for databases. + * Drawing order is lowest to highest. + * Google Earth Enterprise customers can add a side database and set the drawOrder to be either before or after that of the main database. + * Side databases default to a drawing order of 0. + */ + setDrawOrder(drawOrder: number): void; + } + + /** + * A KmlDocument has containers that holds features and styles. + * This container is required if you use shared styles. + * It is recommended that you use shared styles, which require the following. + * + * 1. Define all Styles in a Document. Assign a unique ID to each Style. + * 2. Within a given feature or StyleMap, reference the Style's ID using a styleUrl element. + * + * Note: Shared styles are not inherited by the features in the Document. + */ + export class KmlDocument extends KmlContainer { + + /** + * Returns a list of elements using a particular style URL. + */ + getElementsByStyleUrl(styleUrl: string): KmlObjectList; + + /** + * Returns an array containing the style selectors present in the KML document. + */ + getStyleSelectors(): GEStyleSelectorContainer; + } + + /** + * The KmlPlacemark is a feature with associated Geometry. + */ + export class KmlPlacemark extends KmlFeature { + + /** + * The geometry associated with the placemark. + */ + getGeometry(): KmlGeometry; + + /** + * The geometry associated with the placemark. + */ + setGeometry(geometry: KmlGeometry): void; + } + + /** + * The base class for the three types of balloon windows that can overlay the 3D window. + */ + export class GEAbstractBalloon { + + /** + * The ID of the balloon. + */ + getId(): string; + + /** + * The ID of the balloon. + */ + setId(id: string): void; + + /** + * Determines what the balloon is attached to. + */ + getFeature(): KmlFeature; + + /** + * Determines what the balloon is attached to. + */ + setFeature(feature: KmlFeature): void; + + /** + * Minimum width of the balloon. + */ + getMinWidth(): number; + + /** + * Minimum width of the balloon. + */ + setMinWidth(minWidth: number): void; + + /** + * Minimum height of the balloon. + */ + getMinHeight(): number; + + /** + * Minimum height of the balloon. + */ + setMinHeight(minHeight: number): void; + + /** + * Maximum width of the balloon. + */ + getMaxWidth(): number; + + /** + * Maximum width of the balloon. + */ + setMaxWidth(maxWidth: number): void; + + /** + * Maximum height of the balloon. + */ + getMaxHeight(): number; + + /** + * Maximum height of the balloon. + */ + setMaxHeight(maxHeight: number): void; + + /** + * When true, the balloon frame is displayed with a button that the user + * can click to close the balloon. When false, the balloon frame is just + * a plain frame. + * + * Default is true. + */ + getCloseButtonEnabled(): boolean; + + /** + * When true, the balloon frame is displayed with a button that the user + * can click to close the balloon. When false, the balloon frame is just + * a plain frame. + * + * Default is true. + */ + setCloseButtonEnabled(closeButtonEnabled: boolean): void; + } + + /** + * Base class for GEHtmlStringBalloon and GEHtmlDivBalloon. + */ + export class GEFeatureBalloon extends GEAbstractBalloon {} + + /** + * Creates a balloon that contains HTML. + */ + export class GEHtmlBalloon extends GEAbstractBalloon { + + /** + * The color of the text in the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, it is interpreted as #000000. + */ + getForegroundColor(): string; + + /** + * The color of the text in the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, it is interpreted as #000000. + */ + setForegroundColor(foregroundColor: string): void; + + /** + * The background color of the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, the default is interpreted as #FFFFFF. + */ + getBackgroundColor(): string; + + /** + * The background color of the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, the default is interpreted as #FFFFFF. + */ + setBackgroundColor(backgroundColor: string): void; + } + + /** + * The GEHtmlDivBalloon object creates a balloon based on the contentDiv property. + */ + export class GEHtmlDivBalloon extends GEHtmlBalloon { + + /** + * An HTMLDivElement to be used as the contents of the balloon. + * When the balloon is shown, the HTMLDivElement is attached to the balloon element in the web page. + * You can manipulate this balloon using ordinary HTML DOM techniques. + */ + getContentDiv(): HTMLDivElement; + + /** + * An HTMLDivElement to be used as the contents of the balloon. + * When the balloon is shown, the HTMLDivElement is attached to the balloon element in the web page. + * You can manipulate this balloon using ordinary HTML DOM techniques. + */ + setContentDiv(contentDiv: HTMLElement): void; + } + + /** + * The GEHtmlStringBalloon class represents a balloon based on the contentString. + */ + export class GEHtmlStringBalloon extends GEHtmlBalloon { + + /** + * You can include any HTML using the contentString property. + * When the balloon is visible, the content specified in contentString property, + * is inserted directly into the balloon element in the web page. + */ + getContentString(): string; + + /** + * You can include any HTML using the contentString property. + * When the balloon is visible, the content specified in contentString property, + * is inserted directly into the balloon element in the web page. + */ + setContentString(contentString: string): void; + } + + /** + * The base class for GETimeControl. + */ + export class GEControl {} + + /** + * Represents the time slider object. + */ + export class GETimeControl extends GEControl { + + /** + * Whether the time slider is visible or not. + */ + getVisibility(): GEVisibilityEnum; + + /** + * Specifies whether the control is visible or hidden. + */ + setVisibility(visibility: GEVisibilityEnum): void; + + /** + * Returns the clock rate that the plugin would use, if the play button on the time slider UI was pressed. + * This rate is calculated by the plugin based on the time range currently present in the slider. + */ + getCalculatedRate(): number; + + /** + * Returns a KmlTimeSpan object encompassing the earliest and latest times present in the time slider. + * For more information, refer to the Time chapter of the Developer's Guide. + */ + getExtents(): KmlTimeSpan; + + /** + * Returns an array containing the KmlTimeStamp objects associated with the historical imagery available in this view. + */ + getAvailableImageDates(): KmlObjectList; + + } + + /** + * The GEPlugin is the Google Earth Plugin's main object, and this is the object that is returned to the JavaScript application when you first create a plug-in instance. + * GEPlugin provides factory methods for ructing other objects (placemarks, and so on), and is also used to retrieve the root document objects. + */ + export class GEPlugin { + + /** + * A Specifies that altitudes are at ground level. For Ground overlays, this means that the image will be draped over the terrain. + */ + ALTITUDE_CLAMP_TO_GROUND: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are to be interpreted as meters above or below ground level (i.e. the elevation of the terrain at the location). + */ + ALTITUDE_RELATIVE_TO_GROUND: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are to be interpreted as meters above or below sea level, regardless of the actual elevation of the terrain beneath the object. + * For example, if you set the altitude of an object to 10 meters with an absolute altitude mode, the object will appear to be at ground level if the terrain beneath is also 10 meters above sea level. + * If the terrain is 3 meters above sea level, the object will appear elevated above the terrain by 7 meters. + * If, on the other hand, the terrain is 15 meters above sea level, the object may be completely invisible. + */ + ALTITUDE_ABSOLUTE: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are at sea floor level. + */ + ALTITUDE_CLAMP_TO_SEA_FLOOR: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are to be interpreted as meters above sea floor (i.e. the elevation of the sea floor at the location). + */ + ALTITUDE_RELATIVE_TO_SEA_FLOOR: KmlAltitudeModeEnum; + + /** + * Refresh when the file is loaded and whenever the Link parameters change. This refresh mode is the default. + */ + REFRESH_ON_CHANGE: KmlRefreshModeEnum; + + /** + * Refresh every n seconds (specified in refreshInterval). + */ + REFRESH_ON_INTERVAL: KmlRefreshModeEnum; + + /** + * Refresh when the expiration time is reached. + * If a fetched file has a NetworkLinkControl, the expires time takes precedence over expiration times specified in HTTP headers. + * If no expires time is specified, the HTTP max-age header is used (if present). + * If max-age is not present, the Expires HTTP header is used (if present). + */ + REFRESH_ON_EXPIRE: KmlRefreshModeEnum; + + /** + * Ignore changes in the view. Also ignore viewFormat parameters, if any. + * This view refresh mode is the default. + */ + VIEW_REFRESH_NEVER: KmlViewRefreshModeEnum; + + /** + * Refresh the file only when the user explicitly requests it. + */ + VIEW_REFRESH_ON_REQUEST: KmlViewRefreshModeEnum; + + /** + * Refresh n seconds after movement stops, where n is specified in viewRefreshTime. + */ + VIEW_REFRESH_ON_STOP: KmlViewRefreshModeEnum; + + /** + * Refresh only when the feature's Region becomes active. + */ + VIEW_REFRESH_ON_REGION: KmlViewRefreshModeEnum; + + /** + * Screen coordinates are to be interpreted as a fraction of an item, like an image or Google Earth window. + */ + UNITS_FRACTION: KmlUnitsEnum; + + /** + * Screen coordinates are to be interpreted as pixels from the left or bottom edge. + */ + UNITS_PIXELS: KmlUnitsEnum; + + /** + * Screen coordinates are to be interpreted as pixels from the top or right edge. + */ + UNITS_INSET_PIXELS: KmlUnitsEnum; + + /** + * Apply no color mode effect, i.e. use the base color as is. + */ + COLOR_NORMAL: KmlColorModeEnum; + + /** + * Apply a random linear scale to the base color. See the KML documentation for more details. + */ + COLOR_RANDOM: KmlColorModeEnum; + + /** + * Inherit the color mode from ancestor styles. + */ + COLOR_INHERIT: KmlColorModeEnum; + + /** + * The Earth map type, used with GEOptions' setMapType. + */ + MAP_TYPE_EARTH: GEMapTypeEnum; + + /** + * The Sky map type, used with GEOptions' setMapType. + */ + MAP_TYPE_SKY: GEMapTypeEnum; + + /** + * Hide the UI element. + */ + VISIBILITY_HIDE: GEVisibilityEnum; + + /** + * Show the UI element always. + */ + VISIBILITY_SHOW: GEVisibilityEnum; + + /** + * Automatically show or hide the UI element depending on user interaction. + */ + VISIBILITY_AUTO: GEVisibilityEnum; + + /** + * Specifies that fly-to should happen immediately, without a smooth transition. + */ + SPEED_TELEPORT: number; + + /** + * The Layer ID of the terrain layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_TERRAIN: string; + + /** + * The Layer ID of the roads layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_ROADS: string; + + /** + * The Layer ID of the photorealistic buildings layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_BUILDINGS: string; + + /** + * The Layer ID of the low resolution (gray) buildings layer. + * Use as an argument to getLayerById() or enableLayerById(). + * Note that as photorealistic buildings continue to be created and added to the LAYER_BUILDINGS layer, the low-resolution version of those buildings will be removed from this layer. + * This layer will therefore change over time. + */ + LAYER_BUILDINGS_LOW_RESOLUTION: string; + + /** + * The Layer ID of the borders layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_BORDERS: string; + + /** + * The Layer ID of the trees layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_TREES: string; + + /** + * When using the GEView.hitTest method, this mode samples the globe (the earth's sphere at altitude 0, without terrain or buildings). + */ + HIT_TEST_GLOBE: GEHitTestModeEnum; + + /** + * When using the GEView.hitTest method, this mode samples the earth's terrain (the ground surface, including variations in altitude). + */ + HIT_TEST_TERRAIN: GEHitTestModeEnum; + + /** + * When using the GEView.hitTest method, this mode samples 3D buildings. + */ + HIT_TEST_BUILDINGS: GEHitTestModeEnum; + + /** + * Sets the render state to its default value. Currently, sunlight, Street View, and historical imagery all default to a disabled state. + */ + OPTION_STATE_DEFAULT: GEViewerOptionsValueEnum; + + /** + * Set the render state to on. Passed to the KmlViewerOptions.setOption method. + */ + OPTION_STATE_ENABLED: GEViewerOptionsValueEnum; + + /** + * Set the render state to off. Passed to the KmlViewerOptions.setOption method. + */ + OPTION_STATE_DISABLED: GEViewerOptionsValueEnum; + + /** + * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether the Sun option should be visible. + * Sun can also be enabled/disabled with GEPlugin.getSun. + */ + OPTION_SUNLIGHT: GEViewerOptionsTypeEnum; + + /** + * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether historical imagery should be enabled. + */ + OPTION_HISTORICAL_IMAGERY: GEViewerOptionsTypeEnum; + + /** + * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether Street View should be enabled when the view reaches ground level. + * Note that this applies only to programmatic movement, such as fly-tos; to control whether the user can enter Street View using manual navigation controls, call ge.getPlugin().streetViewEnabled(true). + */ + OPTION_STREET_VIEW: GEViewerOptionsTypeEnum; + + /** + * The feature's visibility is tied to its list item's checkbox state. + */ + LIST_ITEM_CHECK: KmlListItemTypeEnum; + + /** + * When specified for a folder, document or network link, prevents all items from being made visible at once—that is, the user can turn all children off but cannot turn them all on at the same time. + * This setting is useful for containers or network links containing large amounts of data. + */ + LIST_ITEM_CHECK_OFF_ONLY: KmlListItemTypeEnum; + + /** + * Use a normal checkbox for visibility but do not display children in a list view. + * The item's checkbox should allows the user to toggle visibility of the child objects in the viewport. + */ + LIST_ITEM_CHECK_HIDE_CHILDREN: KmlListItemTypeEnum; + + /** + * When specified for a container (a folder or a document), only one of the container's items should be visible at a time. + */ + LIST_ITEM_RADIO_FOLDER: KmlListItemTypeEnum; + + /** + * The large navigation control type, used with GENavigationControl.setControlType(). + */ + NAVIGATION_CONTROL_LARGE: GENavigationControlEnum; + + /** + * The small navigation control type, used with GENavigationControl.setControlType(). + */ + NAVIGATION_CONTROL_SMALL: GENavigationControlEnum; + + /** + * Parse a string of KML and return a handle to the root of the KML object structure that was created. + */ + parseKml(kml: string): KmlObject; + + /** + * Get an element by ID. This is functionally equivalent to getElementByUrl with an unspecified base URL. + * + * For example: getElementByUrl('#foo'). + * + * Usage is when finding objects created with JavaScript, which have unspecified base URLs. + * The object must be a descendant of the DOM before it can be found. + */ + getElementById(id: string): KmlObject; + + /** + * Get an element by URL. A URL consists of the base address and the ID, joined with the # character. + * + * For example: http://www.google.com/bar.kml#here_be_monsters + * + * This applies to objects that are fetched. + * In the case of plugin created objects, the URL is simply #foo. + * The object must be a descendant of the DOM before it can be found. + */ + getElementByUrl(url: string): KmlObject; + + /** + * Get a list of elements by type. + */ + getElementsByType(): KmlObjectList; + + /** + * Creates a placemark on the globe. + * A Placemark is a feature with associated Geometry. + * A Placemark with a Point has an icon associated with it that marks a point on the Earth in the 3D viewer. + * (In the Google Earth 3D viewer, a Point Placemark is the only object you can click or roll over. + * Other Geometry objects do not have an icon in the 3D viewer. + * To allow the user to click in the 3D viewer, you would need to create a MultiGeometry object that contains both a Point and the other Geometry object.) + */ + createPlacemark(id: string): KmlPlacemark; + + /** + * Creates a point on the globe. Specifies the geographic location defined by longitude, latitude, and (optional) altitude. + */ + createPoint(id: string): KmlPoint; + + /** + * Creates a line string on Google Earth. + */ + createLineString(id: string): KmlLineString; + + /** + * Creates a folder. + * A KMLFolder is used to arrange other features hierarchically (Folders, Placemarks, NetworkLinks, or Overlays). + * A feature is visible only if it and all its ancestors are visible. + */ + createFolder(id: string): KmlFolder; + + /** + * Creates level of detail (LOD). + * LOD describes the size of the projected region on the screen that is required in order for the region to be considered active. + * Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + createLod(id: string): KmlLod; + + /** + * Creates a LatLonBox, a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + createLatLonBox(id: string): KmlLatLonBox; + + /** + * Creates a LatLonAltBox, a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + createLatLonAltBox(id: string): KmlLatLonAltBox; + + /** + * Creates a Document. A Document is a container for features and styles. + */ + createDocument(id: string): KmlDocument; + + /** + * Creates a Region in Google Earth. + * A Region contains a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + createRegion(id: string): KmlRegion; + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + createLocation(id: string): KmlLocation; + + /** + * Sets the rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + createOrientation(id: string): KmlOrientation; + + /** + * Sets the scale of a model along the x, y, and z axes in the model's coordinate space. + */ + createScale(id: string): KmlScale; + + /** + * Creates a model. + * A model is a 3D object described in a COLLADA file. + * COLLADA files have a .dae file extension. + * Models are created in their own coordinate space and then located, positioned, and scaled in Google Earth. + */ + createModel(id: string): KmlModel; + + /** + * A Style defines an addressable style group that can be referenced by StyleMaps and features. + */ + createStyle(id: string): KmlStyle; + + /** + * Creates a LinearRing. + * A LinearRing defines a closed line string, typically the outer boundary of a Polygon. + * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. + */ + createLinearRing(id: string): KmlLinearRing; + + /** + * Creates a Polygon. A Polygon is defined by an outer boundary and 0 or more inner boundaries. + */ + createPolygon(id: string): KmlPolygon; + + /** + * Creates an Icon. An icon defines an image associated with an Icon style or overlay. + */ + createIcon(id: string): KmlIcon; + + /** + * Creates a Link. + * A Link specifies the location of KML files fetched by network links, image files used in any overlay, or model files used with the Model object. + */ + createLink(id: string): KmlLink; + + /** + * Creates a GroundOverlay. + * A GroundOverlay draws an image overlay draped onto the terrain. + */ + createGroundOverlay(id: string): KmlGroundOverlay; + + /** + * Creates a NetworkLink. + * A NetworkLink references a KML file or KMZ archive on a local or remote network. + */ + createNetworkLink(id: string): KmlNetworkLink; + + /** + * Creates a ScreenOverlay. + * A ScreenOverlay draws an image overlay fixed to the screen. + */ + createScreenOverlay(id: string): KmlScreenOverlay; + + /** + * Creates a container for one or more geometry primitives associated with the same feature. + */ + createMultiGeometry(id: string): KmlMultiGeometry; + + /** + * Creates a StyleMap. + * A StyleMap maps between two different icon styles. + * Typically, a StyleMap is used to provide separate normal and highlighted styles for a Placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + createStyleMap(id: string): KmlStyleMap; + + /** + * Creates a new LookAt. + * A LookAt element positions the camera view in relation to an object that is being viewed. + */ + createLookAt(id: string): KmlLookAt; + + /** + * Creates a new Camera. + * This element positions the camera relative to the Earth's surface and defines the view direction. + */ + createCamera(id: string): KmlCamera; + + /** + * Creates a new viewer options object. + */ + createViewerOptions(id: string): KmlViewerOptions; + + /** + * Create a KmlTimeStamp object. + * For more information, refer to the Time chapter of the Google Earth API developer's guide. + */ + createTimeStamp(id: string): KmlTimeStamp; + + /** + * Create a KmlTimeSpan object. + * For more information, refer to the Time chapter of the Google Earth API developer's guide. + */ + createTimeSpan(id: string): KmlTimeSpan; + + /** + * Creates a Feature balloon. + */ + createFeatureBalloon(id: string): GEFeatureBalloon; + + /** + * Creates an HTML string balloon. + */ + createHtmlStringBalloon(id: string): GEHtmlStringBalloon; + + /** + * Creates an Html Div Balloon. + */ + createHtmlDivBalloon(id: string): GEHtmlDivBalloon; + + /** + * Returns the currently active balloon, or null. + */ + getBalloon(): GEAbstractBalloon; + + /** + * Sets the given balloon as the active balloon, replacing any existing active balloon. + * If the given feature is visible, then the balloon is displayed. Otherwise, the balloon is hidden. + * + * If the argument is null, then any existing active balloon will be hidden. + */ + setBalloon(newActiveBalloon: GEAbstractBalloon): void; + + /** + * Used for debugging purposes; if this value is not equal to the value returned by getPluginVersion then there is a misconfiguration on the end user's system. + * This check is automatically done during plugin instantiation. + */ + getEarthVersion(): string; + + /** + * The version of the Google Earth Plug-in installed on the end user's machine. + */ + getPluginVersion(): string; + + /** + * The options used to manipulate the behavior of the Google Earth plugin. + */ + getOptions(): GEOptions; + + /** + * The time class used to manipulate the behavior of the Google Earth plugin time. + */ + getTime(): GETime; + + /** + * Controls the window options. + */ + getWindow(): GEWindow; + + /** + * Controls the globe behavior. + */ + getGlobe(): GEGlobe; + + /** + * Displays the dawn to dusk views. + */ + getSun(): GESun; + + /** + * Controls built-in layer behavior. + */ + getLayerRoot(): KmlLayerRoot; + + /** + * Controls the plugin viewport. + */ + getView(): GEView; + + /** + * Controls the navigation controls on the globe. + */ + getNavigationControl(): GENavigationControl; + + /** + * The top-level features currently in the Earth object. + */ + getFeatures(): GEFeatureContainer; + + /** + * Exposes functionality for interacting with KML tours. + */ + getTourPlayer(): GETourPlayer; + + /** + * Exposes functionality for interacting with photo overlays. + */ + getPhotoOverlayViewer(): GEPhotoOverlayViewer; + + /** + * Returns a number between 0 and 100 (inclusive) that indicates the progress of the streaming of imagery for the current view. + * + * A value of 100 means that the imagery is completely streamed in. + */ + getStreamingPercent(): number; + } + + export enum GEEventPhaseEnum {} + export enum KmlListItemTypeEnum {} + export enum KmlColorModeEnum {} + export enum KmlAltitudeModeEnum {} + export enum KmlRefreshModeEnum {} + export enum KmlViewRefreshModeEnum {} + export enum KmlUnitsEnum {} + export enum GEMapTypeEnum {} + export enum GEVisibilityEnum {} + export enum GEHitTestModeEnum {} + export enum GEViewerOptionsValueEnum {} + export enum GENavigationControlEnum {} + export enum GEViewerOptionsTypeEnum {} + +} From 383dc7a3a4fc24a3f1a1fdf17a6e051f1648f0e0 Mon Sep 17 00:00:00 2001 From: Ilia Choly Date: Wed, 17 Aug 2016 12:06:58 -0400 Subject: [PATCH 044/844] fix setter --- google-earth/google-earth.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/google-earth/google-earth.d.ts b/google-earth/google-earth.d.ts index ac10729f17..2e089bd23c 100644 --- a/google-earth/google-earth.d.ts +++ b/google-earth/google-earth.d.ts @@ -1921,7 +1921,7 @@ declare namespace google.earth { /** * The direction that icons are set to point, clockwise, and in degrees. */ - setHeading(): number; + setHeading(heading: number): void; /** * A custom Icon. In KmlIconStyle, the only child element of KmlIcon is href and href is an HTTP address or a local file specification used to load an icon. From f38e0a1a1e12c0d61787a8237daa356d109a3ff3 Mon Sep 17 00:00:00 2001 From: Ilia Choly Date: Wed, 17 Aug 2016 12:10:47 -0400 Subject: [PATCH 045/844] add missing method --- google-earth/google-earth.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/google-earth/google-earth.d.ts b/google-earth/google-earth.d.ts index 2e089bd23c..702524a076 100644 --- a/google-earth/google-earth.d.ts +++ b/google-earth/google-earth.d.ts @@ -2794,6 +2794,11 @@ declare namespace google.earth { */ setLatLng(latitude: number, longitude: number): void; + /** + * Sets the latitude, longitude, and altitide. + */ + setLatLngAlt(latitude: number, longitude: number, altitude: number): void; + /** * The point's latitude, in degrees. */ From ed50b4775d7d49a44d3d39d103aa4f50d3442174 Mon Sep 17 00:00:00 2001 From: Stephen Feest Date: Wed, 17 Aug 2016 21:35:36 +0100 Subject: [PATCH 046/844] Add $transclude function tests These tests try to exercise the different ways that the $transclude can be called including: + With and without specifying the scope explicitly + With and without a clone attach function + With and without specifying the future parent + Using the default and named transclude slots --- angularjs/angular-tests.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index ef3e29b4c8..07f67a7375 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -867,6 +867,26 @@ angular.module('docsTabsExample', []) }; }); +angular.module('multiSlotTranscludeExample', []) + .directive('dropDownMenu', function() { + return { + transclude: { + button: 'button', + list: 'ul', + }, + link: function(scope, element, attrs, ctrl, transclude) { + // without scope + transclude().appendTo(element); + transclude(clone => clone.appendTo(element)); + + // with scope + transclude(scope, clone => clone.appendTo(element)); + transclude(scope, clone => clone.appendTo(element), element, 'button'); + transclude(scope, null, element, 'list').addClass('drop-down-list').appendTo(element); + } + }; + }); + angular.module('componentExample', []) .component('counter', { require: {'ctrl': '^ctrl'}, From 4a97011cb6fd9a584510d569387527a49c70612d Mon Sep 17 00:00:00 2001 From: Lutz Rosema Date: Thu, 18 Aug 2016 10:35:05 +0200 Subject: [PATCH 047/844] Add typedefs for viewport conversion methods --- pdf/pdf-tests.ts | 10 ++++++++++ pdf/pdf.d.ts | 21 ++++++++++++++++++--- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/pdf/pdf-tests.ts b/pdf/pdf-tests.ts index 07b49644cf..238bc291a3 100644 --- a/pdf/pdf-tests.ts +++ b/pdf/pdf-tests.ts @@ -25,6 +25,16 @@ function renderPage(pageNum: number) { var context = canvas.getContext('2d'); canvas.height = viewport.height; canvas.width = viewport.width; + + // + // test viewport conversion methods + // convertToViewportRectangle and normalizeRect are used in the acroforms example: + // https://github.com/mozilla/pdf.js/blob/master/examples/acroforms/forms.js + // + const rect = viewport.convertToViewportRectangle([100,100,0,0]); + const normalizedRect = PDFJS.Util.normalizeRect(rect); + const point = viewport.convertToViewportPoint(100, 100); + const pdfPoint = viewport.convertToPdfPoint(100, 100); // // Render PDF page into canvas context diff --git a/pdf/pdf.d.ts b/pdf/pdf.d.ts index 9fca2d1af5..d13ba6f3cf 100644 --- a/pdf/pdf.d.ts +++ b/pdf/pdf.d.ts @@ -156,9 +156,9 @@ interface PDFPageViewport { transforms: number[]; clone(options: PDFPageViewportOptions): PDFPageViewport; - convertToViewportPoint(): number[]; // [x, y] - convertToViewportRectangle(): number[]; // [x1, y1, x2, y2] - convertToPdfPoint(): number[]; // [x, y] + convertToViewportPoint(x: number, y: number): number[]; // [x, y] + convertToViewportRectangle(rect: number[]): number[]; // [x1, y1, x2, y2] + convertToPdfPoint(x: number, y: number): number[]; // [x, y] } interface PDFAnnotationData { @@ -300,6 +300,19 @@ interface PDFObjects { clear(): void; } +interface PDFJSUtilStatic { + /** + * Normalize rectangle so that (x1,y1) < (x2,y2) + * @param {number[]} rect - the rectangle with [x1,y1,x2,y2] + * + * For coordinate systems whose origin lies in the bottom-left, this + * means normalization to (BL,TR) ordering. For systems with origin in the + * top-left, this means (TL,BR) ordering. + **/ + normalizeRect(rect:number[]): number[]; +} + + interface PDFJSStatic { /** @@ -424,6 +437,8 @@ interface PDFJSStatic { */ isEvalSupported: boolean; + Util: PDFJSUtilStatic; + /** * This is the main entry point for loading a PDF and interacting with it. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR) From 27cbba9005c03368e5d53f11465e96c560f6cdc9 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 21:52:38 +0300 Subject: [PATCH 048/844] Templating type definition --- object-assign/object-assign.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/object-assign/object-assign.d.ts b/object-assign/object-assign.d.ts index 52ef486c72..ad797b25ef 100644 --- a/object-assign/object-assign.d.ts +++ b/object-assign/object-assign.d.ts @@ -4,6 +4,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "object-assign" { + function objectAssign(target: T, source: U): T & U; + function objectAssign(target: T, source1: U, source2: V): T & U & V; + function objectAssign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + function objectAssign(target: T, source1: U, source2: V, source3: W, source4: Q): T & U & V & W & Q; + function objectAssign(target: T, source1: U, source2: V, source3: W, source4: Q, source5: T): T & U & V & W & Q & R; function objectAssign(target: any, ...sources: any[]): any; export = objectAssign; } From d3d99d650b27beaf7f8c436f3e49f96977a5aec9 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 22:35:52 +0300 Subject: [PATCH 049/844] Update react-redux-tests.tsx --- react-redux/react-redux-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux/react-redux-tests.tsx b/react-redux/react-redux-tests.tsx index 7dba7f2fa2..3ebf6ae539 100644 --- a/react-redux/react-redux-tests.tsx +++ b/react-redux/react-redux-tests.tsx @@ -268,8 +268,8 @@ connect(mapStateToProps3)(TodoApp); // return { todos: state.todos }; //} -function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState { - return objectAssign({}, ownProps, { +function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState & TodoProps { + return objectAssign({}, ownProps, dispatchProps, { todos: stateProps.todos[ownProps.userId], addTodo: (text: string) => dispatchProps.addTodo(ownProps.userId, text) }); From a0e4d1fc3740d86e28e8856e981f95fffd5d813d Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 22:41:01 +0300 Subject: [PATCH 050/844] Update react-redux-2.1.2-tests.tsx --- react-redux/react-redux-2.1.2-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux/react-redux-2.1.2-tests.tsx b/react-redux/react-redux-2.1.2-tests.tsx index 7ead497767..a2aade3ff4 100644 --- a/react-redux/react-redux-2.1.2-tests.tsx +++ b/react-redux/react-redux-2.1.2-tests.tsx @@ -233,8 +233,8 @@ connect(mapStateToProps3)(TodoApp); // return { todos: state.todos }; //} -function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState { - return objectAssign({}, ownProps, { +function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState & TodoProps { + return objectAssign({}, ownProps, dispatchProps, { todos: stateProps.todos[ownProps.userId], addTodo: (text: string) => dispatchProps.addTodo(ownProps.userId, text) }); From 7a7510a12d5b1c3c14f45313807c7c1e6092571e Mon Sep 17 00:00:00 2001 From: minodisk Date: Tue, 16 Aug 2016 20:09:18 +0900 Subject: [PATCH 051/844] Format react-router.d.ts --- react-router/react-router.d.ts | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 3fe2538048..41eb1b53ed 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -236,15 +236,15 @@ declare namespace ReactRouter { // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md interface InjectedRouter { - push: (pathOrLoc: H.LocationDescriptor) => void - replace: (pathOrLoc: H.LocationDescriptor) => void - go: (n: number) => void - goBack: () => void - goForward: () => void - setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void - createPath(path: H.Path, query?: H.Query): H.Path - createHref(path: H.Path, query?: H.Query): H.Href - isActive: (pathOrLoc: H.LocationDescriptor, indexOnly?: boolean) => boolean + push: (pathOrLoc: H.LocationDescriptor) => void + replace: (pathOrLoc: H.LocationDescriptor) => void + go: (n: number) => void + goBack: () => void + goForward: () => void + setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void + createPath(path: H.Path, query?: H.Query): H.Path + createHref(path: H.Path, query?: H.Query): H.Href + isActive: (pathOrLoc: H.LocationDescriptor, indexOnly?: boolean) => boolean } function withRouter>(component: C): C @@ -359,7 +359,7 @@ declare module "react-router/lib/useRoutes" { declare module "react-router/lib/PatternUtils" { - export function formatPattern(pattern: string, params: {}): string; + export function formatPattern(pattern: string, params: {}): string; } @@ -419,16 +419,16 @@ declare module "react-router/lib/PropTypes" { } declare module "react-router/lib/browserHistory" { - export default ReactRouter.browserHistory; + export default ReactRouter.browserHistory; } declare module "react-router/lib/hashHistory" { - export default ReactRouter.hashHistory; + export default ReactRouter.hashHistory; } declare module "react-router/lib/match" { - export default ReactRouter.match + export default ReactRouter.match; } @@ -441,11 +441,11 @@ declare module "react-router/lib/useRouterHistory" { } declare module "react-router/lib/createMemoryHistory" { - export default ReactRouter.createMemoryHistory; + export default ReactRouter.createMemoryHistory; } declare module "react-router/lib/withRouter" { - export default ReactRouter.withRouter; + export default ReactRouter.withRouter; } declare module "react-router" { @@ -504,7 +504,7 @@ declare module "react-router" { export type LeaveHook = ReactRouter.LeaveHook export type ParseQueryString = ReactRouter.ParseQueryString export type RedirectFunction = ReactRouter.RedirectFunction - export type RouteComponentProps = ReactRouter.RouteComponentProps; + export type RouteComponentProps = ReactRouter.RouteComponentProps; export type RouteHook = ReactRouter.RouteHook export type StringifyQuery = ReactRouter.StringifyQuery export type RouterListener = ReactRouter.RouterListener From 35324f1700d0658e194785633f9bf95c9d8764e3 Mon Sep 17 00:00:00 2001 From: minodisk Date: Fri, 19 Aug 2016 09:45:19 +0900 Subject: [PATCH 052/844] Add applyRouterMiddleware to react-router --- react-router/react-router.d.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 41eb1b53ed..6d5051f61b 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -88,6 +88,13 @@ declare namespace ReactRouter { function createMemoryHistory(options?: H.HistoryOptions): H.History + interface Middleware { + renderRouterContext: (previous: React.Props<{}>[], props: React.Props<{}>) => React.Props<{}>[] + renderRouteComponent: (previous: React.Props<{}>[], props: React.Props<{}>) => React.Props<{}>[] + } + + function applyRouterMiddleware(...middlewares: Middleware[]): (renderProps: React.Props<{}>) => React.Props<{}>[] + /* components */ interface RouterProps extends React.Props { @@ -97,6 +104,7 @@ declare namespace ReactRouter { onError?: (error: any) => any onUpdate?: () => any parseQueryString?: ParseQueryString + render?: (renderProps: React.Props<{}>) => React.Props<{}>[] stringifyQuery?: StringifyQuery } interface Router extends React.ComponentClass {} @@ -448,6 +456,10 @@ declare module "react-router/lib/withRouter" { export default ReactRouter.withRouter; } +declare module "react-router/lib/applyRouterMiddleware" { + export default ReactRouter.applyRouterMiddleware; +} + declare module "react-router" { import Router from "react-router/lib/Router" @@ -492,6 +504,8 @@ declare module "react-router" { import withRouter from "react-router/lib/withRouter"; + import applyRouterMiddleware from "react-router/lib/applyRouterMiddleware"; + // PlainRoute is defined in the API documented at: // https://github.com/rackt/react-router/blob/master/docs/API.md // but not included in any of the .../lib modules above. @@ -534,7 +548,8 @@ declare module "react-router" { match, useRouterHistory, createMemoryHistory, - withRouter + withRouter, + applyRouterMiddleware } export default Router From d71b7c3821e24a0c167722e675445c6a6b6a9237 Mon Sep 17 00:00:00 2001 From: Chris Manning Date: Fri, 19 Aug 2016 15:13:47 +1200 Subject: [PATCH 053/844] Corrected missing return types to prevent noImplicitAny errors. --- dustjs-linkedin/dustjs-linkedin.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dustjs-linkedin/dustjs-linkedin.d.ts b/dustjs-linkedin/dustjs-linkedin.d.ts index 70bd288a39..9bb05b1424 100644 --- a/dustjs-linkedin/dustjs-linkedin.d.ts +++ b/dustjs-linkedin/dustjs-linkedin.d.ts @@ -89,7 +89,7 @@ declare module "dustjs-linkedin" { * Registers an event listener. Streams accept a single listener for a given event. * @param evt the event. Possible values are data, end, error (maybe more, look in the source). */ - on(evt: string, callback: (data?: any) => any); + on(evt: string, callback: (data?: any) => any): this; pipe(stream: Stream): Stream; } @@ -126,8 +126,8 @@ declare module "dustjs-linkedin" { * @param name the template name. * @param context a plain object or an instance of dust.Context. */ - export function render(name: string, context: any, callback: (err: any, out: string) => any); - export function render(name: string, context: Context, callback: (err: any, out: string) => any); + export function render(name: string, context: any, callback: (err: any, out: string) => any): void; + export function render(name: string, context: Context, callback: (err: any, out: string) => any): void; /** * Compiles and renders source, invoking callback on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required. From 4c7ec690272c58094009b707d4861b46e9982450 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Fri, 19 Aug 2016 16:08:38 +0800 Subject: [PATCH 054/844] http.IncomingMessage no destroy This is [Node v4.x document](https://nodejs.org/dist/latest-v4.x/docs/api/http.html#http_message_destroy_error), please refer this link. --- node/node-4.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node/node-4.d.ts b/node/node-4.d.ts index 02b37f8cb2..e60da8e309 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -632,6 +632,7 @@ declare module "http" { */ statusMessage?: string; socket: net.Socket; + destroy(error?: Error): void; } /** * @deprecated Use IncomingMessage From a94c941c50b85e01aeedea90a5a9dd6ac714aff8 Mon Sep 17 00:00:00 2001 From: Vasiliy Solovey Date: Fri, 19 Aug 2016 12:21:44 +0300 Subject: [PATCH 055/844] Improved aws-lambda type definitions --- aws-lambda/aws-lambda-tests.ts | 19 ++++++++++++++++++- aws-lambda/aws-lambda.d.ts | 14 +++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/aws-lambda/aws-lambda-tests.ts b/aws-lambda/aws-lambda-tests.ts index fd289dcb7f..8b9f53a8ab 100644 --- a/aws-lambda/aws-lambda-tests.ts +++ b/aws-lambda/aws-lambda-tests.ts @@ -9,6 +9,8 @@ var kinesis: lambda.Kinesis; var recordsList: lambda.Record[]; var anyObj: any; var num: number; +var identity: lambda.Identity; +var error: Error; /* Records */ var records: lambda.Records; @@ -46,4 +48,19 @@ context.succeed(str); context.succeed(anyObj); context.succeed(str, anyObj); str = context.awsRequestId; -num = context.getRemainingTimeInMillis(); \ No newline at end of file +num = context.getRemainingTimeInMillis(); +identity = context.identity; + +/* Identity */ +var identity: lambda.Identity; + +str = identity.cognitoIdentityId; +str = identity.cognitoIdentityPoolId; + +/* Callback */ +function callback(cb: lambda.Callback) { + cb(); + cb(null); + cb(error); + cb(null, anyObj); +} \ No newline at end of file diff --git a/aws-lambda/aws-lambda.d.ts b/aws-lambda/aws-lambda.d.ts index cdd8e2f506..081c6e0e3e 100644 --- a/aws-lambda/aws-lambda.d.ts +++ b/aws-lambda/aws-lambda.d.ts @@ -36,8 +36,20 @@ declare module "aws-lambda" { succeed(message: string, object: any): void; awsRequestId: string; getRemainingTimeInMillis(): number; + /** Information about the Amazon Cognito identity provider when invoked through the AWS Mobile SDK. It can be null. */ + identity?: Identity; } + interface Identity { + cognitoIdentityId: string; + cognitoIdentityPoolId: string; + } - export type Callback = (error?: Error, message?: string) => void; + /** + * Optional callback parameter. + * + * @param error – an optional parameter that you can use to provide results of the failed Lambda function execution. + * @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible. + */ + export type Callback = (error?: Error, result?: any) => void; } \ No newline at end of file From fdddacc2e801364decd875dee45bbaf90110631d Mon Sep 17 00:00:00 2001 From: recuedav Date: Fri, 19 Aug 2016 13:54:14 +0200 Subject: [PATCH 056/844] 6586 FIX lodash chain split --- lodash/lodash-3.10-tests.ts | 19 +++++++++++++++++++ lodash/lodash-3.10.d.ts | 21 +++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/lodash/lodash-3.10-tests.ts b/lodash/lodash-3.10-tests.ts index 2616822f6e..3eeff29221 100644 --- a/lodash/lodash-3.10-tests.ts +++ b/lodash/lodash-3.10-tests.ts @@ -9658,6 +9658,25 @@ namespace TestSnakeCase { } } +// _.split +namespace TestSplit { + { + let result: _.LoDashImplicitArrayWrapper; + + result = _('a-b-c').split(); + result = _('a-b-c').split('-'); + result = _('a-b-c').split('-', 2); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + result = _('a-b-c').chain().split(); + result = _('a-b-c').chain().split('-'); + result = _('a-b-c').chain().split('-', 2); + } +} + // _.startCase namespace TestStartCase { { diff --git a/lodash/lodash-3.10.d.ts b/lodash/lodash-3.10.d.ts index aea06a8362..a63d92d0f0 100644 --- a/lodash/lodash-3.10.d.ts +++ b/lodash/lodash-3.10.d.ts @@ -14720,6 +14720,27 @@ declare module _ { snakeCase(): LoDashExplicitWrapper; } + //_.split + interface LoDashImplicitWrapper { + /** + * Splits string by separator. + * + * Note: This method is based on String#split. + * + * @param separator The separator pattern to split by. + * @param limit The length to truncate results to. + * @return Returns the new array with the terms splitted. + */ + split(separator?: RegExp|string, limit?: number): LoDashImplicitArrayWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.split + */ + split(separator?: RegExp|string, limit?: number): LoDashImplicitArrayWrapper; + } + //_.startCase interface LoDashStatic { /** From 0feed49c7d294522da1d9ac7589740303b458b86 Mon Sep 17 00:00:00 2001 From: Marcel Haldemann Date: Fri, 19 Aug 2016 15:19:00 +0200 Subject: [PATCH 057/844] support for cookieOptions.expires to be false (to be valid only until Browser closes) --- express-serve-static-core/express-serve-static-core.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 f83e509e63..745b0e6ab2 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -117,7 +117,7 @@ declare module "express-serve-static-core" { interface CookieOptions { maxAge?: number; signed?: boolean; - expires?: Date; + expires?: Date | boolean; httpOnly?: boolean; path?: string; domain?: string; From c34b986e7b1a52f38e28c649a166d5416e81c561 Mon Sep 17 00:00:00 2001 From: Marcel Haldemann Date: Fri, 19 Aug 2016 15:41:12 +0200 Subject: [PATCH 058/844] support for req.session.cookie.expires to be false added (false means: cookie to remain for only the duration of the user-agent) --- express-session/express-session.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/express-session/express-session.d.ts b/express-session/express-session.d.ts index 156e9404fc..90e1ed07cc 100644 --- a/express-session/express-session.d.ts +++ b/express-session/express-session.d.ts @@ -30,7 +30,7 @@ declare namespace Express { secure?: boolean; httpOnly: boolean; domain?: string; - expires: Date; + expires: Date | boolean; serialize: (name: string, value: string) => string; } } From 3aa72a05675e3be3781f41a15b0d95842994d094 Mon Sep 17 00:00:00 2001 From: Ilia Choly Date: Fri, 19 Aug 2016 11:19:57 -0400 Subject: [PATCH 059/844] document the enum types --- google-earth/google-earth.d.ts | 81 ++++++++++++++++++++++++++++------ 1 file changed, 67 insertions(+), 14 deletions(-) diff --git a/google-earth/google-earth.d.ts b/google-earth/google-earth.d.ts index 702524a076..3c85b96d7f 100644 --- a/google-earth/google-earth.d.ts +++ b/google-earth/google-earth.d.ts @@ -14,6 +14,73 @@ declare namespace google { declare namespace google.earth { + /** + * Specifies the current stage of the flow of events. + */ + export type GEEventPhaseEnum = any; + + /** + * Specifies how a feature should be displayed in a list view. + */ + export type KmlListItemTypeEnum = any; + + /** + * Specifies which color mode effect to apply to the base color. + */ + export type KmlColorModeEnum = any; + + /* + * Specifies how the altitude property is interpreted. + */ + export type KmlAltitudeModeEnum = any; + + /** + * Specifies how the link is refreshed. + */ + export type KmlRefreshModeEnum = any; + + /** + * Specifies how the link is refreshed when the viewport changes. + */ + export type KmlViewRefreshModeEnum = any; + + /** + * Specifies which units a value is specified in. + */ + type KmlUnitsEnum = any; + + /** + * Specifies if the map type is Earth or sky mode. + */ + type GEMapTypeEnum = any; + + /** + * Specifies if a control is always visible, always hidden, + * or visible only when the user intends to use the control. + */ + type GEVisibilityEnum = any; + + /** + * Specifies what to sample when performing a hit test. + */ + type GEHitTestModeEnum = number; + + /** + * Specifies the size of the navigation control. + */ + type GENavigationControlEnum = number; + + /** + * Specifies the state of viewer options, including sunlight, + * Street View, and historical imagery. + */ + type GEViewerOptionsValueEnum = number; + + /* + * Specifies the viewer option types. + */ + type GEViewerOptionsTypeEnum = number; + /** * Whether or not the Google Earth Browser Plug-in and API are supported on the current browser and operating system. */ @@ -3908,18 +3975,4 @@ declare namespace google.earth { getStreamingPercent(): number; } - export enum GEEventPhaseEnum {} - export enum KmlListItemTypeEnum {} - export enum KmlColorModeEnum {} - export enum KmlAltitudeModeEnum {} - export enum KmlRefreshModeEnum {} - export enum KmlViewRefreshModeEnum {} - export enum KmlUnitsEnum {} - export enum GEMapTypeEnum {} - export enum GEVisibilityEnum {} - export enum GEHitTestModeEnum {} - export enum GEViewerOptionsValueEnum {} - export enum GENavigationControlEnum {} - export enum GEViewerOptionsTypeEnum {} - } From ba133509fc0eb90c60f5f172389d68ab2454454c Mon Sep 17 00:00:00 2001 From: Ilia Choly Date: Fri, 19 Aug 2016 11:26:34 -0400 Subject: [PATCH 060/844] use any type --- google-earth/google-earth.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/google-earth/google-earth.d.ts b/google-earth/google-earth.d.ts index 3c85b96d7f..d0adc8c04e 100644 --- a/google-earth/google-earth.d.ts +++ b/google-earth/google-earth.d.ts @@ -63,23 +63,23 @@ declare namespace google.earth { /** * Specifies what to sample when performing a hit test. */ - type GEHitTestModeEnum = number; + type GEHitTestModeEnum = any; /** * Specifies the size of the navigation control. */ - type GENavigationControlEnum = number; + type GENavigationControlEnum = any; /** * Specifies the state of viewer options, including sunlight, * Street View, and historical imagery. */ - type GEViewerOptionsValueEnum = number; + type GEViewerOptionsValueEnum = any; /* * Specifies the viewer option types. */ - type GEViewerOptionsTypeEnum = number; + type GEViewerOptionsTypeEnum = any; /** * Whether or not the Google Earth Browser Plug-in and API are supported on the current browser and operating system. From 5863f2493ea8f12c4925c60d53e6184ffb43104e Mon Sep 17 00:00:00 2001 From: Daniel Niederberger Date: Fri, 19 Aug 2016 17:50:10 +0200 Subject: [PATCH 061/844] Add missing definition In angular you can either write `directive('myDirective', ['$http', function($http) {...}])`, which is minification safe, but it's also possible to write `directive('myDirective', function($http) {...})` which might not be minification safe, but valid angular nonetheless. --- angularjs/angular.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 3c13fd6cf3..fcfde914e3 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -238,6 +238,7 @@ declare namespace angular { * @param directiveFactory An injectable directive factory function. */ directive(name: string, inlineAnnotatedFunction: any[]): IModule; + directive(name: string, injectionFunction: Function): IModule; directive(object: Object): IModule; /** * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. From 2f07f4c429ca54253faa4b2ee072645299b63e48 Mon Sep 17 00:00:00 2001 From: Seth Westphal Date: Fri, 19 Aug 2016 12:27:12 -0500 Subject: [PATCH 062/844] Fix module name. --- auth0-js/auth0-js.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/auth0-js/auth0-js.d.ts b/auth0-js/auth0-js.d.ts index 1ee4ab9d7c..515d52af7e 100644 --- a/auth0-js/auth0-js.d.ts +++ b/auth0-js/auth0-js.d.ts @@ -127,6 +127,6 @@ interface Auth0DelegationToken { declare var Auth0: Auth0Static; -declare module "auth0" { +declare module "auth0-js" { export = Auth0 } From 78d7ae624db6de4963223b5c56d205602c674c65 Mon Sep 17 00:00:00 2001 From: Steve Lam Date: Fri, 19 Aug 2016 12:36:24 -0700 Subject: [PATCH 063/844] export scriptjs module --- scriptjs/scriptjs.d.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/scriptjs/scriptjs.d.ts b/scriptjs/scriptjs.d.ts index c0bf3d0c6d..aa76b4517c 100644 --- a/scriptjs/scriptjs.d.ts +++ b/scriptjs/scriptjs.d.ts @@ -1,6 +1,6 @@ // Type definitions for scriptjs // Project: https://github.com/ded/script.js -// Definitions by: Steve Lam +// Definitions by: Steve Lam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface $script { @@ -12,6 +12,7 @@ interface $script { ready(deps:string | string[], ready:() => void, req?:(missing:string[]) => void): $script; } -declare var $script: $script; - -export = $script; +declare module 'scriptjs'{ + var $script: $script; + export = $script; +} From 6e9b95facc04e268b48be30c605653055c6be046 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 22:37:37 +0300 Subject: [PATCH 064/844] Update object-assign.d.ts --- object-assign/object-assign.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/object-assign/object-assign.d.ts b/object-assign/object-assign.d.ts index ad797b25ef..c3f92b7592 100644 --- a/object-assign/object-assign.d.ts +++ b/object-assign/object-assign.d.ts @@ -8,7 +8,7 @@ declare module "object-assign" { function objectAssign(target: T, source1: U, source2: V): T & U & V; function objectAssign(target: T, source1: U, source2: V, source3: W): T & U & V & W; function objectAssign(target: T, source1: U, source2: V, source3: W, source4: Q): T & U & V & W & Q; - function objectAssign(target: T, source1: U, source2: V, source3: W, source4: Q, source5: T): T & U & V & W & Q & R; + function objectAssign(target: T, source1: U, source2: V, source3: W, source4: Q, source5: R): T & U & V & W & Q & R; function objectAssign(target: any, ...sources: any[]): any; export = objectAssign; } From 912e35ffabf81a20987c185b90eeee616ac6ec1d Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 23:00:49 +0300 Subject: [PATCH 065/844] Update object-assign-tests.ts --- object-assign/object-assign-tests.ts | 80 ++++++++++++++++++++++++---- 1 file changed, 71 insertions(+), 9 deletions(-) diff --git a/object-assign/object-assign-tests.ts b/object-assign/object-assign-tests.ts index 53dfd5e707..d1304422d3 100644 --- a/object-assign/object-assign-tests.ts +++ b/object-assign/object-assign-tests.ts @@ -1,17 +1,79 @@ /// import objectAssign = require("object-assign"); -function assign1() { - var result = objectAssign({hello: "world"}); - return result; +interface Target { + hellow: string; } -function assign2() { - var result = objectAssign({hello: "world"}, {hello: "worlds", second: "extra"}); - return result; +interface Source1 { + source1: string; } -function assign3() { - var result = objectAssign({hello: "world"}, {hello: "worlds", second: "extra"}, {hello: "stop", the: "spinning"}); - return result; +interface Result extends Target, Source1 { + } + +interface Source2 { + source2: string; +} + +interface Result2 extends Result, Source2 { + +} + +interface Source3 { + source3: string; +} + +interface Result3 extends Result2, Source3 { + +} + +interface Source4 { + source4: string; +} + +interface Result4 extends Result4, Source3 { + +} + +interface Source5 { + source2: string; +} + +interface Result5 extends Result4, Source5 { + +} + +function assign1(): Result { + return objectAssign({hellow: "world"}, {source1: "U"}); +} + +function assign2(): Result2 { + return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}); +} + +function assign3(): Result3 { + return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}); +} + +function assign4(): Result4 { + return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}); +} + +function assign5(): Result5 { + return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}, {source5: "R"}); +} + +function assign() { + return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}, {source5: "R"}, { + hellow: "hellow", + source1: "source1", + source2: "source2", + source3: "source3", + source4: "source4", + source5: "source5", + generic: "any" + }); +} + From 3af3e291f296fb37426660fdd042e4a4d00a4b75 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 23:01:15 +0300 Subject: [PATCH 066/844] Update object-assign-tests.ts --- object-assign/object-assign-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/object-assign/object-assign-tests.ts b/object-assign/object-assign-tests.ts index d1304422d3..d285219b24 100644 --- a/object-assign/object-assign-tests.ts +++ b/object-assign/object-assign-tests.ts @@ -38,7 +38,7 @@ interface Result4 extends Result4, Source3 { } interface Source5 { - source2: string; + source5: string; } interface Result5 extends Result4, Source5 { From 3e194fcd32705d0934ed4a545bb2bb96754b48d9 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 23:03:34 +0300 Subject: [PATCH 067/844] Update object-assign-tests.ts --- object-assign/object-assign-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/object-assign/object-assign-tests.ts b/object-assign/object-assign-tests.ts index d285219b24..6b9a898ed4 100644 --- a/object-assign/object-assign-tests.ts +++ b/object-assign/object-assign-tests.ts @@ -33,7 +33,7 @@ interface Source4 { source4: string; } -interface Result4 extends Result4, Source3 { +interface Result4 extends Result3, Source4 { } From f1760b924d1f7b13f6f9c936811fd1a0ac5bb6c7 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 23:06:33 +0300 Subject: [PATCH 068/844] Update react-redux-tests.tsx --- react-redux/react-redux-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux/react-redux-tests.tsx b/react-redux/react-redux-tests.tsx index 3ebf6ae539..7dba7f2fa2 100644 --- a/react-redux/react-redux-tests.tsx +++ b/react-redux/react-redux-tests.tsx @@ -268,8 +268,8 @@ connect(mapStateToProps3)(TodoApp); // return { todos: state.todos }; //} -function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState & TodoProps { - return objectAssign({}, ownProps, dispatchProps, { +function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState { + return objectAssign({}, ownProps, { todos: stateProps.todos[ownProps.userId], addTodo: (text: string) => dispatchProps.addTodo(ownProps.userId, text) }); From 5bd8afe661c476ffbb32a195d7dc2422babd6b2b Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 23:07:41 +0300 Subject: [PATCH 069/844] Update react-redux-2.1.2-tests.tsx --- react-redux/react-redux-2.1.2-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux/react-redux-2.1.2-tests.tsx b/react-redux/react-redux-2.1.2-tests.tsx index a2aade3ff4..7ead497767 100644 --- a/react-redux/react-redux-2.1.2-tests.tsx +++ b/react-redux/react-redux-2.1.2-tests.tsx @@ -233,8 +233,8 @@ connect(mapStateToProps3)(TodoApp); // return { todos: state.todos }; //} -function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState & TodoProps { - return objectAssign({}, ownProps, dispatchProps, { +function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState { + return objectAssign({}, ownProps, { todos: stateProps.todos[ownProps.userId], addTodo: (text: string) => dispatchProps.addTodo(ownProps.userId, text) }); From f340b21d40bf4f2f2f93421953b2ca35c187e33b Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 23:19:38 +0300 Subject: [PATCH 070/844] Fixing broken test due to object-assign type definition change Not familiar with redux but merging and `dispatchProps` in `mergeProps` seems valid since `action` is required property of `DispatchProps` and should come from somewhere. --- react-redux/react-redux-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux/react-redux-tests.tsx b/react-redux/react-redux-tests.tsx index 7dba7f2fa2..3ebf6ae539 100644 --- a/react-redux/react-redux-tests.tsx +++ b/react-redux/react-redux-tests.tsx @@ -268,8 +268,8 @@ connect(mapStateToProps3)(TodoApp); // return { todos: state.todos }; //} -function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState { - return objectAssign({}, ownProps, { +function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState & TodoProps { + return objectAssign({}, ownProps, dispatchProps, { todos: stateProps.todos[ownProps.userId], addTodo: (text: string) => dispatchProps.addTodo(ownProps.userId, text) }); From 52a9758e65b175c1b7f3affd360735714d89ed36 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Fri, 19 Aug 2016 23:23:31 +0300 Subject: [PATCH 071/844] Mirroring test fixes from react-redux-tests.tsx --- react-redux/react-redux-2.1.2-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux/react-redux-2.1.2-tests.tsx b/react-redux/react-redux-2.1.2-tests.tsx index 7ead497767..a2aade3ff4 100644 --- a/react-redux/react-redux-2.1.2-tests.tsx +++ b/react-redux/react-redux-2.1.2-tests.tsx @@ -233,8 +233,8 @@ connect(mapStateToProps3)(TodoApp); // return { todos: state.todos }; //} -function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState { - return objectAssign({}, ownProps, { +function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProps: TodoProps): DispatchProps & TodoState & TodoProps { + return objectAssign({}, ownProps, dispatchProps, { todos: stateProps.todos[ownProps.userId], addTodo: (text: string) => dispatchProps.addTodo(ownProps.userId, text) }); From 1005f869a53b929a767a873bfe6c7201f32d1ef0 Mon Sep 17 00:00:00 2001 From: Paul Oppenheim Date: Fri, 19 Aug 2016 14:29:55 -0700 Subject: [PATCH 072/844] knex allows usage of Buffer types for values --- knex/knex.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/knex/knex.d.ts b/knex/knex.d.ts index 23dc58af82..ec6403ed2c 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -12,7 +12,7 @@ declare module "knex" { type Callback = Function; type Client = Function; - type Value = string|number|boolean|Date|Array|Array|Array|Array; + type Value = string|number|boolean|Date|Array|Array|Array|Array|Buffer; type ColumnName = string|Knex.Raw|Knex.QueryBuilder; type TableName = string|Knex.Raw|Knex.QueryBuilder; From fedccb1e7ad7e2aad3fad61e7de6ef536a8967c5 Mon Sep 17 00:00:00 2001 From: Oliver Joseph Ash Date: Sat, 20 Aug 2016 10:31:54 +0100 Subject: [PATCH 073/844] RxJS DOM: ajax doesn't return Error, throws instead RxJS DOM does not return AjaxErrorResponse, it throws it. Observable errors are currently not modelled in the typings. --- rx-dom/rx-dom.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/rx-dom/rx-dom.d.ts b/rx-dom/rx-dom.d.ts index 5a42810600..e0d4369c60 100644 --- a/rx-dom/rx-dom.d.ts +++ b/rx-dom/rx-dom.d.ts @@ -110,13 +110,13 @@ declare module Rx.DOM { function touchstart(element: Element, selector?:Function, useCapture?:boolean):Rx.Observable; // Ajax - function ajax(url:string):Rx.Observable; - function ajax(settings:AjaxSettings):Rx.Observable; - function get(url:string):Rx.Observable; + function ajax(url:string):Rx.Observable; + function ajax(settings:AjaxSettings):Rx.Observable; + function get(url:string):Rx.Observable; function getJSON(url:string):Rx.Observable; - function post(url:string, body:any):Rx.Observable; + function post(url:string, body:any):Rx.Observable; function jsonpRequest(url:string):Rx.Observable; - function jsonpRequest(settings:JsonpSettings):Rx.Observable; + function jsonpRequest(settings:JsonpSettings):Rx.Observable; // Server-Sent Events function fromEventSource(url:string, openObservable?:Rx.Observer):Rx.Observable; @@ -139,4 +139,4 @@ declare module Rx.DOM { declare module "rx.DOM" { export default Rx.DOM; -} \ No newline at end of file +} From 88c5e9aca6c4a8c065cca68204ba36b8c2ffdb73 Mon Sep 17 00:00:00 2001 From: Maciej Suchecki Date: Sat, 20 Aug 2016 11:54:27 +0200 Subject: [PATCH 074/844] Modified color properties to accept gradients in whole Highcharts lib (#10700) Updated setExtremes method to accept 'eventArguments' parameter Updated 'crosshair' field to accept boolean value in HighchartsAxisOptions --- highcharts/highcharts.d.ts | 76 +++++++++++++++++++------------------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index de1e5343ca..bfe5a70235 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -240,7 +240,7 @@ interface HighchartsPlotBands { * Border color for the plot band. Also requires borderWidth to be set. * @default null */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * Border width for the plot band. Also requires borderColor to be set. * @default 0 @@ -471,7 +471,7 @@ interface HighchartsAxisOptions { /** * Configure a crosshair that follows either the mouse pointer or the hovered point. */ - crosshair?: HighchartsCrosshairObject; + crosshair?: HighchartsCrosshairObject | boolean; /** * For a datetime axis, the scale will automatically adjust to the appropriate unit. This member gives the default * string representations used for each unit. For an overview of the replacement codes, see dateFormat. @@ -556,7 +556,7 @@ interface HighchartsAxisOptions { * The color of the line marking the axis itself. * @default '#C0D0E0'. */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the line marking the axis itself. * @default 1 @@ -820,7 +820,7 @@ interface HighchartsAxisOptions { interface HighchartsColorAxisDataClass { from?: number; to?: number; - color?: string; + color?: string | HighchartsGradient; name?: string; } @@ -906,7 +906,7 @@ interface HighchartsColorAxisOptions { * The color of the line marking the axis itself. * @default '#C0D0E0' */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the line marking the axis itself. * @default 0 @@ -926,7 +926,7 @@ interface HighchartsColorAxisOptions { * The color of the marker. * @default 'gray' */ - color?: string; + color?: string | HighchartsGradient; }; /** * The maximum value of the axis in terms of map point values. If null, the max value is automatically calculated. @@ -1382,7 +1382,7 @@ interface HighchartsShadow { /** * @default 'black' */ - color?: string; + color?: string | HighchartsGradient; /** * @default 1 */ @@ -1491,7 +1491,7 @@ interface HighchartsChartOptions { * The color of the outer chart border. * @default '#4572A7' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the outer chart border. * @default 0 @@ -1721,7 +1721,7 @@ interface HighchartsChartOptions { interface HighchartsCSSObject { background?: string; border?: string; - color?: string; + color?: string | HighchartsGradient; cursor?: string; font?: string; fontFamily?: string; @@ -2429,7 +2429,7 @@ interface HighchartsLegendOptions { * The color of the drawn border around the legend. * @default '#909090' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border corner radius of the legend. * @default 0 @@ -2724,7 +2724,7 @@ interface HighchartsPaneBackground { /** * @default 'silver' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * @default 1 */ @@ -2803,7 +2803,7 @@ interface HighchartsDataLabels { * The border color for the data label. * @since 2.2.1 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border radius in pixels for the data label. * @default 0 @@ -2820,7 +2820,7 @@ interface HighchartsDataLabels { * The text color for the data labels. * @default null */ - color?: string; + color?: string | HighchartsGradient; /** * Whether to hide data labels that are outside the plot area. By default, the data label is moved inside the plot * area according to the overflow option. @@ -3066,7 +3066,7 @@ interface HighchartsMarkerState { * The color of the point marker's outline. When null, the series' or point's color is used. * @default '#FFFFFF', '#000000' for select state */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the point marker's outline. * @default 0 @@ -3276,7 +3276,7 @@ interface HighchartsAreaZone { * Defines the color of the series. * @since 4.1.0 */ - color?: string; + color?: string | HighchartsGradient; /** * A name for the dash style to use for the graph. * @since 4.1.0 @@ -3321,7 +3321,7 @@ interface HighchartsRangeDataLabels { * @default undefined * @since 2.2.1 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border radius in pixels for the data label. * @default 0 @@ -3338,7 +3338,7 @@ interface HighchartsRangeDataLabels { * The text color for the data labels. * @default null */ - color?: string; + color?: string | HighchartsGradient; /** * Whether to hide data labels that are outside the plot area. By default, the data label is moved inside the plot * area according to the overflow option. @@ -3471,7 +3471,7 @@ interface HighchartsDial { * @default 'black' * @since 2.3.0 */ - backgroundColor?: string; + backgroundColor?: string | HighchartsGradient; /** * The length of the dial's base part, relative to the total radius or length of the dial. * @default '70%'. @@ -3490,7 +3490,7 @@ interface HighchartsDial { * @default 'silver' * @since 2.3.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the gauge dial border in pixels. * @default 0 @@ -3524,14 +3524,14 @@ interface HighchartsPivot { * @default 'black' * @since 2.3.0 */ - backgroundColor?: string; + backgroundColor?: string | HighchartsGradient; /** * The border or stroke color of the pivot. In able to change this, the borderWidth must also be set to something * other than the default 0. * @default 'silver' * @since 2.3.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border or stroke width of the pivot. * @default 0 @@ -3554,7 +3554,7 @@ interface HighchartsTreeMapLevel { * Can set borderColor on all points which lies on the same level. * @since 4.1.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * et the dash style of the border of all the point which lies on the level. * @since 4.1.0 @@ -3569,7 +3569,7 @@ interface HighchartsTreeMapLevel { * Can set a color on all points which lies on the same level. * @since 4.1.0 */ - color?: string; + color?: string | HighchartsGradient; /** * Can set the options of dataLabels on each point which lies on the level. * @default undefined @@ -3594,7 +3594,7 @@ interface HighchartsTreeMapLevel { } /** - * General options for all series types + * General options for all series types. */ interface HighchartsSeriesChart { /** @@ -3615,7 +3615,7 @@ interface HighchartsSeriesChart { * specified. In bar type series it applies to the bars unless a color is specified per point. The default value is * pulled from the options.colors array. */ - color?: string; + color?: string | HighchartsGradient; /** * Polar charts only. Whether to connect the ends of a line series plot across the extremes. * @default true @@ -3860,7 +3860,7 @@ interface HighchartsAreaChart extends HighchartsSeriesChart { * A separate color for the graph line. By default the line takes the color of the series, but the lineColor setting * allows setting a separate color for the line without altering the fillColor. */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * A separate color for the negative part of the area. * @since 3.0 @@ -3902,7 +3902,7 @@ interface HighchartsBarChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the border surrounding each column or bar. * @default 0 @@ -4263,7 +4263,7 @@ interface HighchartsFunnelChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4385,7 +4385,7 @@ interface HighchartsHeatMapChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the border surrounding each column or bar. * @default 0 @@ -4468,7 +4468,7 @@ interface HighchartsPieChart extends HighchartsSeriesChart { * borderless pies. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4573,7 +4573,7 @@ interface HighchartsPyramidChart extends HighchartsSeriesChart { * The color of the border surrounding each slice * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each slice * @default 1 @@ -4688,7 +4688,7 @@ interface HighchartsTreeMapChart extends HighchartsSeriesChart { * The color of the border surrounding each tree map item. * @default '#E0E0E0' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4783,7 +4783,7 @@ interface HighchartsWaterFallChart extends HighchartsBarChart { * @default '#333333' * @since 3.0 */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The color used specifically for positive point columns. When not specified, the general series color is used. */ @@ -4834,7 +4834,7 @@ interface HighchartsIndividualSeriesOptions { * specified. In bar type series it applies to the bars unless a color is specified per point. The default * value is pulled from the options.colors array. */ - color?: string; + color?: string | HighchartsGradient; /** * You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user * that the points and lines can be clicked. @@ -4949,7 +4949,7 @@ interface HighchartsDataPoint { * Individual color for the point. By default the color is pulled from the global colors array. * @default undefined */ - color?: string; + color?: string | HighchartsGradient; /** * Serves a purpose only if a colorAxis object is defined in the chart options. This value will decide which color * the point gets from the scale of the colorAxis. @@ -5173,7 +5173,7 @@ interface HighchartsTitleOptions { } interface HighchartsCrosshairObject { - color?: string; + color?: string | HighchartsGradient; width?: number; dashStyle?: string; //Solid ShortDash ShortDot ShortDashDot ShortDashDotDot Dot Dash LongDash DashDot LongDashDot LongDashDotDot zIndex?: number; @@ -5200,7 +5200,7 @@ interface HighchartsTooltipOptions extends HighchartsSeriesTooltipOptions { * The color of the tooltip border. When null, the border takes the color of the corresponding series or point. * @default null */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The radius of the rounded border corners. * @default 3 @@ -5602,7 +5602,7 @@ interface HighchartsAxisObject { * @param {boolean | HighchartsAnimation} animation When true, the resize will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. * @since 1.2.0 */ - setExtremes(min?: number, max?: number, redraw?: boolean, animation?: boolean | HighchartsAnimation): void; + setExtremes(min?: number, max?: number, redraw?: boolean, animation?: boolean | HighchartsAnimation, eventArguments?: any): void; /** * Update the title of the axis after render time. * @param {HighchartsAxisTitle} title The new title options on the same format as given in xAxis.title. From 502f0dfb79a3f1587a4b49b0c756bdcd12dbd1b1 Mon Sep 17 00:00:00 2001 From: Ezekiel Victor Date: Sat, 20 Aug 2016 02:55:51 -0700 Subject: [PATCH 075/844] definitions for karma-fixture (#10724) * definitions for karma-fixture * return type here can be any object with any keys (arbitrary JSON) * Update karma-fixture.d.ts --- karma-fixture/karma-fixture-tests.ts | 10 ++++++++++ karma-fixture/karma-fixture.d.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 karma-fixture/karma-fixture-tests.ts create mode 100644 karma-fixture/karma-fixture.d.ts diff --git a/karma-fixture/karma-fixture-tests.ts b/karma-fixture/karma-fixture-tests.ts new file mode 100644 index 0000000000..b3a1d8e51c --- /dev/null +++ b/karma-fixture/karma-fixture-tests.ts @@ -0,0 +1,10 @@ +/// + +fixture.setBase('fixtures/base/path'); +fixture.load('test1.html', 'test1.json', false); +fixture.load('test1.html', 'test2.html', 'test1.json'); +fixture.set('', true); +fixture.set('', ''); +fixture.cleanup(); +fixture.el.firstChild; +JSON.stringify(fixture.json[0]); diff --git a/karma-fixture/karma-fixture.d.ts b/karma-fixture/karma-fixture.d.ts new file mode 100644 index 0000000000..8e4d18fd47 --- /dev/null +++ b/karma-fixture/karma-fixture.d.ts @@ -0,0 +1,27 @@ +// Type definitions for karma-fixture 0.2.6 +// Project: https://github.com/billtrik/karma-fixture +// Definitions by: Ezekiel Victor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module fixture { + var el: HTMLElement; + var json: any[]; + + function load(...files: string[]): any; + function load(file1: string, append?: boolean): any; + function load(file1: string, file2: string, append?: boolean): any; + function load(file1: string, file2: string, file3: string, append?: boolean): any; + function load(file1: string, file2: string, file3: string, file4: string, append?: boolean): any; + function load(file1: string, file2: string, file3: string, file4: string, file5: string, append?: boolean): any; + + function set(...htmlStrs: string[]): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, append?: boolean): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, htmlStr2: string, append?: boolean): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, append?: boolean): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, append?: boolean): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, htmlStr5: string, append?: boolean): HTMLElement|HTMLElement[]; + + function cleanup(): void; + + function setBase(fixtureBasePath: string): void; +} From cf44ce85f33d43a9e1717efbf47ea6a11560b302 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Sat, 20 Aug 2016 12:56:15 +0300 Subject: [PATCH 076/844] source5 type should be generic R (#10726) * source5 should be of generic type R * Update simple-assign-tests.ts --- simple-assign/simple-assign-tests.ts | 79 +++++++++++++++++++++++++--- simple-assign/simple-assign.d.ts | 2 +- 2 files changed, 72 insertions(+), 9 deletions(-) diff --git a/simple-assign/simple-assign-tests.ts b/simple-assign/simple-assign-tests.ts index 3970356f5b..d39583bc8c 100644 --- a/simple-assign/simple-assign-tests.ts +++ b/simple-assign/simple-assign-tests.ts @@ -1,15 +1,78 @@ - /// -import assign = require("simple-assign"); +import simpleAssign = require("simple-assign"); -function assign1() { - return assign({hello: "world"}); +interface Target { + hellow: string; } -function assign2() { - return assign({hello: "world"}, {hello: "worlds", second: "extra"}); +interface Source1 { + source1: string; } -function assign3() { - return assign({hello: "world"}, {hello: "worlds", second: "extra"}, {hello: "stop", the: "spinning"}); +interface Result extends Target, Source1 { + +} + +interface Source2 { + source2: string; +} + +interface Result2 extends Result, Source2 { + +} + +interface Source3 { + source3: string; +} + +interface Result3 extends Result2, Source3 { + +} + +interface Source4 { + source4: string; +} + +interface Result4 extends Result3, Source4 { + +} + +interface Source5 { + source5: string; +} + +interface Result5 extends Result4, Source5 { + +} + +function assign1(): Result { + return simpleAssign({hellow: "world"}, {source1: "U"}); +} + +function assign2(): Result2 { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}); +} + +function assign3(): Result3 { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}); +} + +function assign4(): Result4 { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}); +} + +function assign5(): Result5 { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}, {source5: "R"}); +} + +function assign() { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}, {source5: "R"}, { + hellow: "hellow", + source1: "source1", + source2: "source2", + source3: "source3", + source4: "source4", + source5: "source5", + generic: "any" + }); } diff --git a/simple-assign/simple-assign.d.ts b/simple-assign/simple-assign.d.ts index 3b9229bd65..7c44236f4c 100644 --- a/simple-assign/simple-assign.d.ts +++ b/simple-assign/simple-assign.d.ts @@ -8,7 +8,7 @@ declare module "simple-assign" { function simpleAssign(target: T, source1: U, source2: V): T & U & V; function simpleAssign(target: T, source1: U, source2: V, source3: W): T & U & V & W; function simpleAssign(target: T, source1: U, source2: V, source3: W, source4: Q): T & U & V & W & Q; - function simpleAssign(target: T, source1: U, source2: V, source3: W, source4: Q, source5: T): T & U & V & W & Q & R; + function simpleAssign(target: T, source1: U, source2: V, source3: W, source4: Q, source5: R): T & U & V & W & Q & R; function simpleAssign(target: any, ...sources: any[]): any; export = simpleAssign; } From 8ff9b5f4ad74ecdecbf3aa6acf1dcc0efc43b70f Mon Sep 17 00:00:00 2001 From: Gary Blackwood Date: Sat, 20 Aug 2016 10:59:25 +0100 Subject: [PATCH 077/844] Update ravenjs configuration options. (#10732) The configuration options available to the ravenjs client have changed since the initial creation of the type definitions. See: https://docs.sentry.io/hosted/clients/javascript/config/ --- ravenjs/ravenjs.d.ts | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/ravenjs/ravenjs.d.ts b/ravenjs/ravenjs.d.ts index 53cf4ad9cb..ae891a7cda 100644 --- a/ravenjs/ravenjs.d.ts +++ b/ravenjs/ravenjs.d.ts @@ -1,6 +1,6 @@ // Type definitions for Raven.js // Project: https://github.com/getsentry/raven-js -// Definitions by: Santi Albo , Benjamin Pannell +// Definitions by: Santi Albo , Benjamin Pannell , Gary Blackwood // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var Raven: RavenStatic; @@ -10,15 +10,15 @@ declare module 'raven-js' { } interface RavenOptions { - /** The log level associated with this event. Default: error */ - level?: string; - /** The name of the logger used by Sentry. Default: javascript */ logger?: string; /** The release version of the application you are monitoring with Sentry */ release?: string; + /** The environment in which the application is running. */ + environment?: string; + /** The name of the server or device that the client is running on */ serverName?: string; @@ -39,11 +39,6 @@ interface RavenOptions { [id: string]: string; }; - extra?: any; - - /** In some cases you may see issues where Sentry groups multiple events together when they should be separate entities. In other cases, Sentry simply doesn’t group events together because they’re so sporadic that they never look the same. */ - fingerprint?: string[]; - /** A function which allows mutation of the data payload right before being sent to Sentry */ dataCallback?: (data: any) => any; @@ -53,8 +48,17 @@ interface RavenOptions { /** By default, Raven does not truncate messages. If you need to truncate characters for whatever reason, you may set this to limit the length. */ maxMessageLength?: number; + /** Enables/disables automatic collection of breadcrumbs. Default: true. */ + autoBreadcrumbs?: any; + + /** The max number of breadcrumb captures. Default: 100. */ + maxBreadcrumbs?: number; + /** Override the default HTTP data transport handler. */ transport?: (options: RavenTransportOptions) => void; + + /** Allow the use of a Sentry DSN with a private key. Default: false. */ + allowSecretKey?: boolean; } interface RavenStatic { From 55c3e254e151847b8d37ca09b1a566ad4a48a66a Mon Sep 17 00:00:00 2001 From: York Yao Date: Sat, 20 Aug 2016 18:00:18 +0800 Subject: [PATCH 078/844] fix type of iconlib (#10716) * fix type of iconlib * better type of icon lib and theme --- json-editor/json-editor.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/json-editor/json-editor.d.ts b/json-editor/json-editor.d.ts index cbb0c9c29c..280c17e70f 100644 --- a/json-editor/json-editor.d.ts +++ b/json-editor/json-editor.d.ts @@ -39,7 +39,7 @@ type JSONEditorOptions = { /** * The icon library to use for the editor. */ - iconlib?: boolean; + iconlib?: "bootstrap2" | "bootstrap3" | "foundation2" | "foundation3" | "jqueryui" | "fontawesome3" | "fontawesome4"; /** * If true, objects can only contain properties defined with the properties keyword. */ @@ -75,7 +75,7 @@ type JSONEditorOptions = { /** * The CSS theme to use. */ - theme?: string; + theme?: "barebones" | "html" | "bootstrap2" | "bootstrap3" | "foundation3" | "foundation4" | "foundation5" | "foundation6" | "jqueryui"; /** * If true, only required properties will be included by default. */ From 5a7c84346ba1a65a2bdb362ba4166e1267567d56 Mon Sep 17 00:00:00 2001 From: Jack Moore Date: Sat, 20 Aug 2016 16:52:29 -0500 Subject: [PATCH 079/844] New definition for universal-router --- universal-router/universal-router-tests.ts | 99 ++++++++++++++++++++++ universal-router/universal-router.d.ts | 70 +++++++++++++++ 2 files changed, 169 insertions(+) create mode 100644 universal-router/universal-router-tests.ts create mode 100644 universal-router/universal-router.d.ts diff --git a/universal-router/universal-router-tests.ts b/universal-router/universal-router-tests.ts new file mode 100644 index 0000000000..922ca137ad --- /dev/null +++ b/universal-router/universal-router-tests.ts @@ -0,0 +1,99 @@ +/// + +import {ActionContext, Params, resolve } from "universal-router"; + +// Test 1 +const routes1 = [ + { + path: "/one", + action: () => "Page One" + }, + { + path: "/two", + action: () => "Page Two" + } +]; + +resolve(routes1, { path: "/one" }) + .then(result => console.log(result)); + +// Test 2 +const routes2 = [ + { + path: "/hello/:username", + action: (context: ActionContext) => `Welcome, ${context.params["username"]}!` + } +]; + +resolve(routes2, { path: "/hello/john" }) + .then(result => console.log(result)); + + +// Test 3 +const routes3 = [ + { + path: "/hello/:username", + action: (ctx: ActionContext, { username }: Params) => `Welcome, ${username}!` + } +]; + +resolve(routes3, { path: "/hello/john" }) + .then(result => console.log(result)); + + +// Test 4 +const routes4 = [ + { + path: "/hello", + action: () => new Promise(resolve => { + setTimeout(() => resolve("Welcome!"), 1000); + }) + } +]; + +resolve(routes4, { path: "/hello" }) + .then(result => console.log(result)); + +// Test 5 +const routes5 = [ + { + path: "/hello/:username", + async action(ctx: ActionContext, { username }: Params) { + const waitable = async (name: string) => { + console.log(`Welcome ${name}`); + } + await waitable(username); + } + } +]; + +resolve(routes5, { path: "/hello/john" }) + .then(result => console.log(result)); + +// Test 6 +const routes6 = [ + { path: "/one", action: () => "

    Page One

    " }, + { path: "/two", action: () => "

    Page Two

    " } +]; + +resolve(routes6, { path: "/one" }).then(result => { + document.body.innerHTML = result || "

    Not Found

    "; +}); + +// Test 7 +interface Render { + render: typeof render; +} + +const routes7 = [ + { path: "/one", action: ({ render: func }: ActionContext & Render) => func("

    Page One

    ") }, + { path: "/two", action: ({ render: func }: ActionContext & Render) => func("

    Page Two

    ") } +]; + +function render(component: string) { + return new Promise(resolve => { + console.log(`Rendering... ${component}`); + }); +} + +resolve>(routes7, { path: "/one", render }); diff --git a/universal-router/universal-router.d.ts b/universal-router/universal-router.d.ts new file mode 100644 index 0000000000..3ddac31265 --- /dev/null +++ b/universal-router/universal-router.d.ts @@ -0,0 +1,70 @@ +// Type definitions for universal-router +// Project: https://github.com/kriasoft/universal-router +// Definitions by: Jack Moore +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "universal-router" { + /** + * Params is a key/value object that represents extracted URL paramters. Each + * URL parameter resolves to a string. + */ + export interface Params { + [key: string]: string; + } + + /** + * Context represents the context that is passed as the second argument + * passed to resolve. By default, it only is require to contain a path, but + * can be extended by the way of generics. + */ + export interface Context { + path: string; + } + + /** + * ActionContext is similar to Context, with the exception of an added params + * object. ActionContext is passed as the first argument to the action + * function. + */ + export interface ActionContext extends Context { + params: Params; + } + + /** + * A Route is a singular route in your application. It contains a path, an + * action function, and optional children which are an array of Route. + * + * @template C User context that is made union with ActionContext. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + */ + export interface Route { + path: string, + action: (ctx: ActionContext & C, params: Params) => R | Promise | undefined, + children?: Routes + } + + /** + * Routes in an array of type Route. + * @template C User context that is made union with ActionContext. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + */ + export type Routes = Route[]; + + /** + * Resolve function that is given routes and a path or context object. + * Returns a Promise that resolves to result of the action function of the + * matched route. + * + * @template C User context that is made union with Context. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + * + * @param {Routes | Route} routes - Single route or array of routes. + * @param {string | String | Context & C} pathOrContext - path to resolve or + * context object that contains the path along with other data. + * @return {Promise} - Result of matched action function wrapped in a Promsie. + */ + export function resolve(routes: Routes | Route, pathOrContext: string | String | Context & C): Promise +} \ No newline at end of file From 0e58c8bc430f3a60e3ff367fde631f7b317fba08 Mon Sep 17 00:00:00 2001 From: Jack Moore Date: Sat, 20 Aug 2016 17:05:32 -0500 Subject: [PATCH 080/844] Changed undefined return type to void --- universal-router/universal-router.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/universal-router/universal-router.d.ts b/universal-router/universal-router.d.ts index 3ddac31265..6acba5c179 100644 --- a/universal-router/universal-router.d.ts +++ b/universal-router/universal-router.d.ts @@ -39,9 +39,9 @@ declare module "universal-router" { * returns a Promise, R can be the type the Promise resolves to. */ export interface Route { - path: string, - action: (ctx: ActionContext & C, params: Params) => R | Promise | undefined, - children?: Routes + path: string; + action: (ctx: ActionContext & C, params: Params) => R | Promise | void; + children?: Routes; } /** From af265f26cb0ec397caccb340b319d18d967b760b Mon Sep 17 00:00:00 2001 From: Rotem Harel Date: Sun, 21 Aug 2016 15:45:53 +0200 Subject: [PATCH 081/844] Adding missing method definitions to diff-match-patch --- diff-match-patch/diff-match-patch.d.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/diff-match-patch/diff-match-patch.d.ts b/diff-match-patch/diff-match-patch.d.ts index 028fe9d65c..35d0ede3e2 100644 --- a/diff-match-patch/diff-match-patch.d.ts +++ b/diff-match-patch/diff-match-patch.d.ts @@ -5,6 +5,13 @@ declare module "diff-match-patch" { type Diff = [number, string]; + export class Patch { + diffs: Diff[]; + start1: number; + start2: number; + length1: number; + length2: number; + } export class diff_match_patch { static new (): diff_match_patch; @@ -31,6 +38,12 @@ declare module "diff-match-patch" { diff_levenshtein(diffs: Diff[]): number; diff_toDelta(diffs: Diff[]): string; diff_fromDelta(text1: string, delta: string): Diff[]; + + patch_make(text1, text2: string): Patch[]; + patch_deepCopy(patches: Patch[]): Patch[]; + patch_apply(patches: Patch[], text: string): [string, boolean[]]; + patch_fromText(text: string): Patch[]; + patch_toText(patches: Patch[]): string; } export var DIFF_DELETE: number; From 9b891bddf49bfd18bf9596143f544d9a6066988f Mon Sep 17 00:00:00 2001 From: Rotem Harel Date: Sun, 21 Aug 2016 15:51:36 +0200 Subject: [PATCH 082/844] Fixed a missing parameter type. --- diff-match-patch/diff-match-patch.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/diff-match-patch/diff-match-patch.d.ts b/diff-match-patch/diff-match-patch.d.ts index 35d0ede3e2..617944ff82 100644 --- a/diff-match-patch/diff-match-patch.d.ts +++ b/diff-match-patch/diff-match-patch.d.ts @@ -39,7 +39,7 @@ declare module "diff-match-patch" { diff_toDelta(diffs: Diff[]): string; diff_fromDelta(text1: string, delta: string): Diff[]; - patch_make(text1, text2: string): Patch[]; + patch_make(text1: string, text2: string): Patch[]; patch_deepCopy(patches: Patch[]): Patch[]; patch_apply(patches: Patch[], text: string): [string, boolean[]]; patch_fromText(text: string): Patch[]; From 675907148aa12cce0aa1d5237f7d0d9d419d287a Mon Sep 17 00:00:00 2001 From: Rotem Harel Date: Sun, 21 Aug 2016 16:03:00 +0200 Subject: [PATCH 083/844] Second parameter to is optional, first one can be a Diff[]. --- diff-match-patch/diff-match-patch.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/diff-match-patch/diff-match-patch.d.ts b/diff-match-patch/diff-match-patch.d.ts index 617944ff82..b648363ead 100644 --- a/diff-match-patch/diff-match-patch.d.ts +++ b/diff-match-patch/diff-match-patch.d.ts @@ -39,7 +39,7 @@ declare module "diff-match-patch" { diff_toDelta(diffs: Diff[]): string; diff_fromDelta(text1: string, delta: string): Diff[]; - patch_make(text1: string, text2: string): Patch[]; + patch_make(text1: any, text2?: string): Patch[]; patch_deepCopy(patches: Patch[]): Patch[]; patch_apply(patches: Patch[], text: string): [string, boolean[]]; patch_fromText(text: string): Patch[]; From dc124b25ba5bdffd722576a6eaa6595deb8a35e6 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 7 Aug 2016 23:38:46 -0400 Subject: [PATCH 084/844] reverts to interfaces --- mongoose/mongoose-tests.ts | 52 +- mongoose/mongoose.d.ts | 4661 ++++++++++++++++++------------------ 2 files changed, 2302 insertions(+), 2411 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 9aebb3ea1c..12d84cef3e 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -52,7 +52,7 @@ mongoose.model('Actor', new mongoose.Schema({ }), 'collectionName', true).find({}); mongoose.model('Actor').find({}); mongoose.modelNames()[0].toLowerCase(); -new (new mongoose.Mongoose()).Mongoose().connect(''); +new (new mongoose.Mongoose(9, 8, 7)).Mongoose(1, 2, 3).connect(''); mongoose.plugin(cb, {}).connect(''); mongoose.set('test', 'value'); mongoose.set('debug', function(collectionName: any, methodName: any, arg1: any, arg2: any) {}); @@ -136,7 +136,6 @@ conn1.model('myModel', new mongoose.Schema({}), 'myCol').find(); interface IStatics { staticMethod1: (a: number) => string; } -conn1.model<{}, IStatics>('').staticMethod1; conn1.modelNames()[0].toLowerCase(); conn1.config.hasOwnProperty(''); conn1.db.bufferMaxEntries; @@ -350,7 +349,7 @@ new mongoose.Schema({ * section document.js * http://mongoosejs.com/docs/api.html#document-js */ -var doc: mongoose.Document; +var doc: mongoose.MongooseDocument; doc.$isDefault('path').valueOf(); doc.depopulate('path'); doc.equals(doc).valueOf(); @@ -465,7 +464,7 @@ mongooseArray.length; * http://mongoosejs.com/docs/api.html#types-documentarray-js */ // The constructor is private api, but we'll use it to test -var documentArray: mongoose.Types.DocumentArray = +var documentArray: mongoose.Types.DocumentArray = new mongoose.Types.DocumentArray(); documentArray.create({}).errors; documentArray.id(new Buffer('hi')); @@ -500,7 +499,7 @@ var objectId: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromHexStr objectId = new mongoose.Types.ObjectId(12345); objectId.getTimestamp(); /* practical examples */ -export interface IManagerSchema extends mongoose.Document { +export interface IManagerSchema extends mongoose.MongooseDocument { user: mongoose.Schema.Types.ObjectId; } export var ManagerSchema = new mongoose.Schema({ @@ -530,7 +529,7 @@ embeddedDocument.execPopulate(); * section query.js * http://mongoosejs.com/docs/api.html#query-js */ -var query: mongoose.Query; +var query: mongoose.Query; query.$where('').$where(cb); query.all(99).all('path', 99); query.and([{ color: 'green' }, { status: 'ok' }]).and([]); @@ -761,8 +760,9 @@ schemaArray.sparse(true); * section schema/string.js * http://mongoosejs.com/docs/api.html#schema-string-js */ +var MongoDocument: mongoose.Document; var schemastring: mongoose.Schema.Types.String = new mongoose.Schema.Types.String('hello'); -schemastring.checkRequired(234, new mongoose.Document()).valueOf(); +schemastring.checkRequired(234, MongoDocument).valueOf(); schemastring.enum(['hi', 'a', 'b']).enum('hi').enum({}); schemastring.lowercase().lowercase(); schemastring.match(/re/, 'error').match(/re/); @@ -790,7 +790,7 @@ documentarray.sparse(true); * http://mongoosejs.com/docs/api.html#schema-number-js */ var schemanumber: mongoose.Schema.Types.Number = new mongoose.Schema.Types.Number('num', {}); -schemanumber.checkRequired(999, new mongoose.Document()).valueOf(); +schemanumber.checkRequired(999, MongoDocument).valueOf(); schemanumber.max(999, 'error').max(999); schemanumber.min(999, 'error').min(999); /* static properties */ @@ -803,7 +803,7 @@ schemanumber.sparse(true); * http://mongoosejs.com/docs/api.html#schema-date-js */ var schemadate: mongoose.Schema.Types.Date = new mongoose.Schema.Types.Date('99'); -schemadate.checkRequired([], new mongoose.Document()).valueOf(); +schemadate.checkRequired([], MongoDocument).valueOf(); schemadate.expires(99).expires('now'); schemadate.max(new Date(), 'error').max(new Date('')); schemadate.min(new Date(), 'error').min(new Date('')); @@ -817,7 +817,7 @@ schemadate.sparse(true); * http://mongoosejs.com/docs/api.html#schema-buffer-js */ var schemabuffer: mongoose.Schema.Types.Buffer = new mongoose.Schema.Types.Buffer('99'); -schemabuffer.checkRequired(999, new mongoose.Document()).valueOf(); +schemabuffer.checkRequired(999, MongoDocument).valueOf(); /* static properties */ mongoose.Schema.Types.Buffer.schemaName.toLowerCase(); /* inherited properties */ @@ -840,7 +840,7 @@ schemaboolean.sparse(true); */ var schemaobjectid: mongoose.Schema.Types.ObjectId = new mongoose.Schema.Types.ObjectId('99'); schemaobjectid.auto(true).auto(false); -schemaobjectid.checkRequired(99, new mongoose.Document()).valueOf(); +schemaobjectid.checkRequired(99, MongoDocument).valueOf(); /* static properties */ mongoose.Schema.Types.ObjectId.schemaName.toLowerCase(); /* inherited properties */ @@ -1078,7 +1078,7 @@ var MongoModel = mongoose.model('MongoModel', new mongoose.Schema({ required: true } }), 'myCollection', true); -MongoModel.$where('indexOf("val") !== -1').exec(function (err, docs) { +MongoModel.find({}).$where('indexOf("val") !== -1').exec(function (err, docs) { docs[0].save(); }); MongoModel.findById(999, function (err, doc) { @@ -1310,7 +1310,7 @@ LocModel.find() }); }); }); -LocModel.$where('') +LocModel.find({}).$where('') .exec(function (err, locations) { locations[0].name; locations[1].openingTimes; @@ -1346,10 +1346,22 @@ LocModel.geoSearch({}, { interface IStatics { staticMethod2: (a: number) => string; } -var StaticModel = mongoose.model('Location'); -StaticModel.staticMethod2(9).toUpperCase(); -(new StaticModel()).save(function (err, doc) { - doc.openingTimes; - doc.model('').staticMethod2; -}); -StaticModel.model('').staticMethod2; \ No newline at end of file +interface MyDocument extends mongoose.Document { + prop: string; + method: () => void; +} +interface MyModel extends mongoose.Model { + staticProp: string; + staticMethod: () => void; +} +interface ModelStruct { + doc: MyDocument, + model: MyModel +} +var mySchema = new mongoose.Schema({}); +export var Final: MyModel = mongoose.connection.model('Final', mySchema); +Final.findOne(function (err: any, doc: MyDocument) { + doc.save(); + doc.remove(); + doc.model(null, null); +}); \ No newline at end of file diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 421129320f..430b3a2b0c 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -27,43 +27,43 @@ * is just a simple heuristic to keep track of our progress. * * TODO for version 4.x [updated][tested]: - * [x][x] index.js - * [x][x] querystream.js - * [x][x] connection.js - * [x][x] utils.js - * [x][x] browser.js - * [x][x] drivers/node-mongodb-native/collection.js - * [x][x] drivers/node-mongodb-native/connection.js - * [x][x] error/messages.js - * [x][x] error/validation.js - * [x][x] error.js - * [x][x] querycursor.js - * [x][x] virtualtype.js - * [x][x] schema.js - * [x][x] document.js - * [x][x] types/subdocument.js - * [x][x] types/array.js - * [x][x] types/documentarray.js - * [x][x] types/buffer.js - * [x][x] types/objectid.js - * [x][x] types/embedded.js - * [x][x] query.js - * [x][x] schema/array.js - * [x][x] schema/string.js - * [x][x] schema/documentarray.js - * [x][x] schema/number.js - * [x][x] schema/date.js - * [x][x] schema/buffer.js - * [x][x] schema/boolean.js - * [x][x] schema/objectid.js - * [x][x] schema/mixed.js - * [x][x] schema/embedded.js - * [x][x] aggregate.js - * [x][x] schematype.js - * [x][x] promise.js - * [x][x] ES6Promise.js - * [x][x] model.js - * [x][x] collection.js + * [x][ ] index.js + * [x][ ] querystream.js + * [x][ ] connection.js + * [x][ ] utils.js + * [x][ ] browser.js + * [x][ ] drivers/node-mongodb-native/collection.js + * [x][ ] drivers/node-mongodb-native/connection.js + * [x][ ] error/messages.js + * [x][ ] error/validation.js + * [x][ ] error.js + * [x][ ] querycursor.js + * [x][ ] virtualtype.js + * [x][ ] schema.js + * [x][ ] document.js + * [x][ ] types/subdocument.js + * [x][ ] types/array.js + * [x][ ] types/documentarray.js + * [x][ ] types/buffer.js + * [x][ ] types/objectid.js + * [x][ ] types/embedded.js + * [x][ ] query.js + * [x][ ] schema/array.js + * [x][ ] schema/string.js + * [x][ ] schema/documentarray.js + * [x][ ] schema/number.js + * [x][ ] schema/date.js + * [x][ ] schema/buffer.js + * [x][ ] schema/boolean.js + * [x][ ] schema/objectid.js + * [x][ ] schema/mixed.js + * [x][ ] schema/embedded.js + * [x][ ] aggregate.js + * [x][ ] schematype.js + * [x][ ] promise.js + * [x][ ] ES6Promise.js + * [x][ ] model.js + * [x][ ] collection.js */ /* @@ -84,70 +84,26 @@ declare module "mongoose" { * Some mongoose classes have the same name as the native JS classes * Keep references to native classes using a "Native" prefix */ - type NativeBuffer = Buffer; - type NativeDate = Date; - type NativeError = Error; - - /* - * Public API - */ + class NativeBuffer extends global.Buffer {} + class NativeDate extends global.Date {} + class NativeError extends global.Error {} /* * section index.js * http://mongoosejs.com/docs/api.html#index-js */ - - /* Class constructors */ - export var Aggregate: typeof _mongoose.Aggregate; - export var CastError: typeof _mongoose.CastError; - export var Collection: _mongoose.Collection; - export var Connection: typeof _mongoose.Connection; - export var Document: typeof _mongoose.Document; export var DocumentProvider: any; - export var Error: typeof _mongoose.Error; - export var Model: _mongoose.ModelConstructor<{}>; - export var Mongoose: { - // recursive constructor - new(...args: any[]): typeof mongoose; - } - - /** - * To assign your own promise library: - * - * 1. Include this somewhere in your code: - * mongoose.Promise = YOUR_PROMISE; - * - * 2. Include this somewhere in your main .d.ts file: - * type MongoosePromise = YOUR_PROMISE; - */ - - export var Promise: any; - export var PromiseProvider: any; - export var Query: typeof _mongoose.ModelQuery; - export var Schema: typeof _mongoose.Schema; - export var SchemaType: typeof _mongoose.SchemaType; - export var SchemaTypes: typeof _mongoose.Schema.Types; - export var Types: { - Subdocument: typeof _mongoose.Types.Subdocument; - Array: typeof _mongoose.Types.Array; - DocumentArray: typeof _mongoose.Types.DocumentArray; - Buffer: typeof _mongoose.Types.Buffer; - ObjectId: typeof _mongoose.Types.ObjectId; - Embedded: typeof _mongoose.Types.Embedded; - } - export var VirtualType: typeof _mongoose.VirtualType; + export var Model: Model; + // recursive constructor + export var Mongoose: new(...args: any[]) => typeof mongoose; + export var SchemaTypes: typeof Schema.Types; /** Expose connection states for user-land */ export var STATES: Object /** The default connection of the mongoose module. */ - export var connection: _mongoose.Connection; + export var connection: Connection; /** The node-mongodb-native driver Mongoose uses. */ export var mongo: typeof mongodb; - /** - * The mquery query builder Mongoose uses. - * Currently there is no mquery type definition. - */ - export var mquery: any; /** The Mongoose version */ export var version: string; @@ -158,10 +114,10 @@ declare module "mongoose" { * @returns pseudo-promise wrapper around this */ export function connect(uris: string, - options?: _mongoose.MongooseConnectOptions, - callback?: (err: mongodb.MongoError) => void): _mongoose.MongooseThenable; + options?: ConnectOptions, + callback?: (err: mongodb.MongoError) => void): MongooseThenable; export function connect(uris: string, - callback?: (err: mongodb.MongoError) => void): _mongoose.MongooseThenable; + callback?: (err: mongodb.MongoError) => void): MongooseThenable; /** * Creates a Connection instance. @@ -171,20 +127,20 @@ declare module "mongoose" { * @param options options to pass to the driver * @returns the created Connection object */ - export function createConnection(): _mongoose.Connection; + export function createConnection(): Connection; export function createConnection(uri: string, - options?: _mongoose.MongooseConnectOptions - ): _mongoose.Connection; + options?: ConnectOptions + ): Connection; export function createConnection(host: string, database_name: string, port?: number, - options?: _mongoose.MongooseConnectOptions - ): _mongoose.Connection; + options?: ConnectOptions + ): Connection; /** * Disconnects all connections. * @param fn called after all connection close. * @returns pseudo-promise wrapper around this */ - export function disconnect(fn?: (error: any) => void): _mongoose.MongooseThenable; + export function disconnect(fn?: (error: any) => void): MongooseThenable; /** Gets mongoose options */ export function get(key: string): any; @@ -197,10 +153,8 @@ declare module "mongoose" { * @param collection (optional, induced from model name) * @param skipInit whether to skip initialization (defaults to false) */ - export function model(name: string, schema?: _mongoose.Schema, collection?: string, - skipInit?: boolean): _mongoose.ModelConstructor; - export function model(name: string, schema?: _mongoose.Schema, collection?: string, - skipInit?: boolean): Statics & _mongoose.ModelConstructor; + export function model(name: string, schema?: Schema, collection?: string, + skipInit?: boolean): Model; /** * Returns an array of model names created on this instance of Mongoose. @@ -219,2388 +173,2313 @@ declare module "mongoose" { /** Sets mongoose options */ export function set(key: string, value: any): void; + type MongooseThenable = typeof mongoose & _MongooseThenable; + interface _MongooseThenable { + /** + * Ability to use mongoose object as a pseudo-promise so .connect().then() + * and .disconnect().then() are viable. + */ + then(onFulfill?: () => void | TRes | PromiseLike, + onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; + + /** + * Ability to use mongoose object as a pseudo-promise so .connect().then() + * and .disconnect().then() are viable. + */ + catch(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; + } + + class CastError extends Error { + /** + * The Mongoose CastError constructor + * @param type The name of the type + * @param value The value that failed to cast + * @param path The path a.b.c in the doc where this cast error occurred + * @param reason The original error that was thrown + */ + constructor(type: string, value: any, path: string, reason?: NativeError); + } /* - * All the types that are exposed for type checking. + * section querystream.js + * http://mongoosejs.com/docs/api.html#querystream-js + * + * QueryStream can only be accessed using query#stream(), we only + * expose its interface here to enable type-checking. */ - export type Aggregate = _mongoose.Aggregate; - export type CastError = _mongoose.CastError; - export type Collection = _mongoose.Collection; - export type Connection = _mongoose.Connection; - export type Document = _mongoose.Document; - export type Error = _mongoose.Error; - export type ValidationError = _mongoose.ValidationError; + interface QueryStream extends stream.Stream { + /** + * Provides a Node.js 0.8 style ReadStream interface for Queries. + * @event data emits a single Mongoose document + * @event error emits when an error occurs during streaming. This will emit before the close event. + * @event close emits when the stream reaches the end of the cursor or an error occurs, or the stream + * is manually destroyed. After this event, no more events are emitted. + */ + constructor(query: Query, options?: { + /** + * optional function which accepts a mongoose document. The return value + * of the function will be emitted on data. + */ + transform?: Function; + [other: string]: any; + }): QueryStream; - /** Document created from model constructors. */ - export type model = _mongoose.Model; - /** Model Constructor. */ - export type Model = _mongoose.ModelConstructor; + /** + * Destroys the stream, closing the underlying cursor, which emits the close event. + * No more events will be emitted after the close event. + */ + destroy(err?: NativeError): void; - export type Mongoose = typeof mongoose; - export type Promise = _mongoose._MongoosePromise; - export type Query = _mongoose.Query; - export type QueryCursor = _mongoose.QueryCursor; - export type QueryStream = _mongoose.QueryStream; - export type Schema = _mongoose.Schema; - namespace Schema { - namespace Types { - export type Array = _mongoose.Schema._Types.Array; - export type String = _mongoose.Schema._Types.String; - export type DocumentArray = _mongoose.Schema._Types.DocumentArray; - export type Number = _mongoose.Schema._Types.Number; - export type Date = _mongoose.Schema._Types.Date; - export type Buffer = _mongoose.Schema._Types.Buffer; - export type Boolean = _mongoose.Schema._Types.Boolean; - export type Bool = _mongoose.Schema._Types.Boolean; - export type ObjectId = _mongoose.Schema._Types.ObjectId; - export type Oid = _mongoose.Schema._Types.ObjectId; - export type Mixed = _mongoose.Schema._Types.Mixed; - export type Object = _mongoose.Schema._Types.Mixed; - export type Embedded = _mongoose.Schema._Types.Embedded; - } + /** Pauses this stream. */ + pause(): void; + /** Pipes this query stream into another stream. This method is inherited from NodeJS Streams. */ + pipe(destination: T, options?: { end?: boolean; }): T; + /** Resumes this stream. */ + resume(): void; + + /** Flag stating whether or not this stream is paused. */ + paused: boolean; + /** Flag stating whether or not this stream is readable. */ + readable: boolean; } - export type SchemaType = _mongoose.SchemaType; - namespace Types { - export type Subdocument = _mongoose.Types.Subdocument; - export type Array = _mongoose.Types.Array; - export type DocumentArray = _mongoose.Types.DocumentArray; - export type Buffer = _mongoose.Types.Buffer; - export type ObjectId = _mongoose.Types.ObjectId; - export type Embedded = _mongoose.Types.Embedded; + + /* + * section connection.js + * http://mongoosejs.com/docs/api.html#connection-js + * + * The Connection class exposed by require('mongoose') + * is actually the driver's NativeConnection class. + * connection.js defines a base class that the native + * versions extend. See: + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js + */ + abstract class ConnectionBase extends events.EventEmitter { + /** + * For practical reasons, a Connection equals a Db. + * @param base a mongoose instance + * @event connecting Emitted when connection.{open,openSet}() is executed on this connection. + * @event connected Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios. + * @event open Emitted after we connected and onOpen is executed on all of this connections models. + * @event disconnecting Emitted when connection.close() was executed. + * @event disconnected Emitted after getting disconnected from the db. + * @event close Emitted after we disconnected and onClose executed on all of this connections models. + * @event reconnected Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection. + * @event error Emitted when an error occurs on this connection. + * @event fullsetup Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected. + * @event all Emitted in a replica-set scenario, when all nodes specified in the connection string are connected. + */ + constructor(base: typeof mongoose); + + /** + * Opens the connection to MongoDB. + * @param mongodb://uri or the host to which you are connecting + * @param database database name + * @param port database port + * @param options Mongoose forces the db option forceServerObjectId false and cannot be overridden. + * Mongoose defaults the server auto_reconnect options to true which can be overridden. + * See the node-mongodb-native driver instance for options that it understands. + * Options passed take precedence over options included in connection strings. + */ + open(connection_string: string, database?: string, port?: number, + options?: ConnectionOpenOptions, callback?: (err: any) => void): any; + + /** + * Opens the connection to a replica set. + * @param uris comma-separated mongodb:// URIs + * @param database database name if not included in uris + * @param options passed to the internal driver + */ + openSet(uris: string, database?: string, options?: ConnectionOpenSetOptions, + callback?: (err: any) => void): any; + + /** Closes the connection */ + close(callback?: (err: any) => void): _MongoosePromise; + + /** + * Retrieves a collection, creating it if not cached. + * Not typically needed by applications. Just talk to your collection through your model. + * @param name name of the collection + * @param options optional collection options + */ + collection(name: string, options?: Object): Collection; + + /** + * Defines or retrieves a model. + * When no collection argument is passed, Mongoose produces a collection name by passing + * the model name to the utils.toCollectionName method. This method pluralizes the name. + * If you don't like this behavior, either pass a collection name or set your schemas + * collection name option. + * @param name the model name + * @param schema a schema. necessary when defining a model + * @param collection name of mongodb collection (optional) if not given it will be induced from model name + * @returns The compiled model + */ + model(name: string, schema?: Schema, collection?: string): Model; + + /** Returns an array of model names created on this connection. */ + modelNames(): string[]; + + /** A hash of the global options that are associated with this connection */ + config: Object; + + /** The mongodb.Db instance, set when the connection is opened */ + db: mongodb.Db; + + /** A hash of the collections associated with this connection */ + collections: { [index: string]: Collection }; + + /** + * Connection ready state + * 0 = disconnected + * 1 = connected + * 2 = connecting + * 3 = disconnecting + * Each state change emits its associated event name. + */ + readyState: number; } - export type VirtualType = _mongoose.VirtualType; - export type ConnectionOptions = _mongoose.MongooseConnectOptions; + interface ConnectionOptionsBase { + /** passed to the connection db instance */ + db?: any; + /** passed to the connection server instance(s) */ + server?: any; + /** passed to the connection ReplSet instance */ + replset?: any; + /** username for authentication */ + user?: string; + /** password for authentication */ + pass?: string; + /** options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) */ + auth?: any; + } - /** Private */ - namespace _mongoose { - /* - * section index.js - * http://mongoosejs.com/docs/api.html#index-js - */ - type MongooseThenable = typeof mongoose & _MongooseThenable; - interface _MongooseThenable { + /** See the node-mongodb-native driver instance for options that it understands. */ + interface ConnectionOpenOptions extends ConnectionOptionsBase { + /** mongoose-specific options */ + config?: { /** - * Ability to use mongoose object as a pseudo-promise so .connect().then() - * and .disconnect().then() are viable. + * set to false to disable automatic index creation for all + * models associated with this connection. */ - then(onFulfill?: () => void | TRes | PromiseLike, - onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; - - /** - * Ability to use mongoose object as a pseudo-promise so .connect().then() - * and .disconnect().then() are viable. - */ - catch(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; - } - - class CastError extends _mongoose.Error { - /** - * The Mongoose CastError constructor - * @param type The name of the type - * @param value The value that failed to cast - * @param path The path a.b.c in the doc where this cast error occurred - * @param reason The original error that was thrown - */ - constructor(type: string, value: any, path: string, reason?: NativeError); - } - - interface MongooseConnectOptions extends - ConnectionOpenOptions, - ConnectionOpenSetOptions {} - - /* - * section querystream.js - * http://mongoosejs.com/docs/api.html#querystream-js - * - * QueryStream can only be accessed using query#stream(), we only - * expose its interface here to enable type-checking. - */ - interface QueryStream extends stream.Stream { - /** - * Provides a Node.js 0.8 style ReadStream interface for Queries. - * @event data emits a single Mongoose document - * @event error emits when an error occurs during streaming. This will emit before the close event. - * @event close emits when the stream reaches the end of the cursor or an error occurs, or the stream - * is manually destroyed. After this event, no more events are emitted. - */ - constructor(query: Query, options?: { - /** - * optional function which accepts a mongoose document. The return value - * of the function will be emitted on data. - */ - transform?: Function; - [other: string]: any; - }): QueryStream; - - /** - * Destroys the stream, closing the underlying cursor, which emits the close event. - * No more events will be emitted after the close event. - */ - destroy(err?: NativeError): void; - - /** Pauses this stream. */ - pause(): void; - /** Pipes this query stream into another stream. This method is inherited from NodeJS Streams. */ - pipe(destination: T, options?: { end?: boolean; }): T; - /** Resumes this stream. */ - resume(): void; - - /** Flag stating whether or not this stream is paused. */ - paused: boolean; - /** Flag stating whether or not this stream is readable. */ - readable: boolean; - } - - /* - * section connection.js - * http://mongoosejs.com/docs/api.html#connection-js - * - * The Connection class exposed by require('mongoose') - * is actually the driver's NativeConnection class. - * connection.js defines a base class that the native - * versions extend. See: - * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js - */ - abstract class ConnectionBase extends events.EventEmitter { - /** - * For practical reasons, a Connection equals a Db. - * @param base a mongoose instance - * @event connecting Emitted when connection.{open,openSet}() is executed on this connection. - * @event connected Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios. - * @event open Emitted after we connected and onOpen is executed on all of this connections models. - * @event disconnecting Emitted when connection.close() was executed. - * @event disconnected Emitted after getting disconnected from the db. - * @event close Emitted after we disconnected and onClose executed on all of this connections models. - * @event reconnected Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection. - * @event error Emitted when an error occurs on this connection. - * @event fullsetup Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected. - * @event all Emitted in a replica-set scenario, when all nodes specified in the connection string are connected. - */ - constructor(base: typeof mongoose); - - /** - * Opens the connection to MongoDB. - * @param mongodb://uri or the host to which you are connecting - * @param database database name - * @param port database port - * @param options Mongoose forces the db option forceServerObjectId false and cannot be overridden. - * Mongoose defaults the server auto_reconnect options to true which can be overridden. - * See the node-mongodb-native driver instance for options that it understands. - * Options passed take precedence over options included in connection strings. - */ - open(connection_string: string, database?: string, port?: number, - options?: ConnectionOpenOptions, callback?: (err: any) => void): any; - - /** - * Opens the connection to a replica set. - * @param uris comma-separated mongodb:// URIs - * @param database database name if not included in uris - * @param options passed to the internal driver - */ - openSet(uris: string, database?: string, options?: ConnectionOpenSetOptions, - callback?: (err: any) => void): any; - - /** Closes the connection */ - close(callback?: (err: any) => void): _MongoosePromise; - - /** - * Retrieves a collection, creating it if not cached. - * Not typically needed by applications. Just talk to your collection through your model. - * @param name name of the collection - * @param options optional collection options - */ - collection(name: string, options?: Object): Collection; - - /** - * Defines or retrieves a model. - * When no collection argument is passed, Mongoose produces a collection name by passing - * the model name to the utils.toCollectionName method. This method pluralizes the name. - * If you don't like this behavior, either pass a collection name or set your schemas - * collection name option. - * @param name the model name - * @param schema a schema. necessary when defining a model - * @param collection name of mongodb collection (optional) if not given it will be induced from model name - * @returns The compiled model - */ - model(name: string, schema?: Schema, collection?: string): ModelConstructor; - model(name: string, schema?: Schema, collection?: string): Statics & ModelConstructor; - - /** Returns an array of model names created on this connection. */ - modelNames(): string[]; - - /** A hash of the global options that are associated with this connection */ - config: Object; - - /** The mongodb.Db instance, set when the connection is opened */ - db: mongodb.Db; - - /** A hash of the collections associated with this connection */ - collections: { [index: string]: Collection }; - - /** - * Connection ready state - * 0 = disconnected - * 1 = connected - * 2 = connecting - * 3 = disconnecting - * Each state change emits its associated event name. - */ - readyState: number; - } - - interface ConnectionOptionsBase { - /** passed to the connection db instance */ - db?: any; - /** passed to the connection server instance(s) */ - server?: any; - /** passed to the connection ReplSet instance */ - replset?: any; - /** username for authentication */ - user?: string; - /** password for authentication */ - pass?: string; - /** options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) */ - auth?: any; - } - - /** See the node-mongodb-native driver instance for options that it understands. */ - interface ConnectionOpenOptions extends ConnectionOptionsBase { - /** mongoose-specific options */ - config?: { - /** - * set to false to disable automatic index creation for all - * models associated with this connection. - */ - autoIndex?: boolean; - }; - } - - /** See the node-mongodb-native driver instance for options that it understands. */ - interface ConnectionOpenSetOptions extends ConnectionOptionsBase { - /** - * If true, enables High Availability support for mongos - * If connecting to multiple mongos servers, set the mongos option to true. - */ - mongos?: boolean; - } - - /* - * section drivers/node-mongodb-native/collection.js - * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js - */ - interface Collection extends CollectionBase { - /** - * Collection constructor - * @param name name of the collection - * @param conn A MongooseConnection instance - * @param opts optional collection options - */ - new(name: string, conn: Connection, opts?: Object): Collection; - /** Formatter for debug print args */ - $format(arg: any): string; - /** Debug print helper */ - $print(name: any, i: any, args: any[]): void; - /** Retreives information about this collections indexes. */ - getIndexes(): any; - } - - /* - * section drivers/node-mongodb-native/connection.js - * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js - */ - class Connection extends ConnectionBase { - /** - * Switches to a different database using the same connection pool. - * @param name The database name - * @returns New Connection Object - */ - useDb(name: string): Connection; - - /** Expose the possible connection states. */ - static STATES: Object; - } - - /* - * section error/validation.js - * http://mongoosejs.com/docs/api.html#error-validation-js - */ - class ValidationError extends Error { - /** Console.log helper */ - toString(): string; - } - - /* - * section error.js - * http://mongoosejs.com/docs/api.html#error-js - */ - class Error extends global.Error { - /** - * MongooseError constructor - * @param msg Error message - */ - constructor(msg: string); - - /** - * The default built-in validator error messages. These may be customized. - * As you might have noticed, error messages support basic templating - * {PATH} is replaced with the invalid document path - * {VALUE} is replaced with the invalid value - * {TYPE} is replaced with the validator type such as "regexp", "min", or "user defined" - * {MIN} is replaced with the declared min value for the Number.min validator - * {MAX} is replaced with the declared max value for the Number.max validator - */ - static messages: Object; - - /** For backwards compatibility. Same as mongoose.Error.messages */ - static Messages: Object; - } - - /* - * section querycursor.js - * http://mongoosejs.com/docs/api.html#querycursor-js - * - * Callback signatures are from: http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close - * QueryCursor can only be accessed by query#cursor(), we only - * expose its interface to enable type-checking. - */ - interface QueryCursor extends stream.Readable { - /** - * A QueryCursor is a concurrency primitive for processing query results - * one document at a time. A QueryCursor fulfills the Node.js streams3 API, - * in addition to several other mechanisms for loading documents from MongoDB - * one at a time. - * Unless you're an advanced user, do not instantiate this class directly. - * Use Query#cursor() instead. - * @param options query options passed to .find() - * @event cursor Emitted when the cursor is created - * @event error Emitted when an error occurred - * @event data Emitted when the stream is flowing and the next doc is ready - * @event end Emitted when the stream is exhausted - */ - constructor(query: Query, options: Object): QueryCursor; - - /** Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error. */ - close(callback?: (error: any, result: any) => void): _MongoosePromise; - - /** - * Execute fn for every document in the cursor. If fn returns a promise, - * will wait for the promise to resolve before iterating on to the next one. - * Returns a promise that resolves when done. - * @param callback executed when all docs have been processed - */ - eachAsync(fn: (doc: Model) => any, callback?: (err: any) => void): _MongoosePromise>; - - /** - * Get the next document from this cursor. Will return null when there are - * no documents left. - */ - next(callback?: (err: any) => void): _MongoosePromise; - } - - /* - * section virtualtype.js - * http://mongoosejs.com/docs/api.html#virtualtype-js - */ - class VirtualType { - /** This is what mongoose uses to define virtual attributes via Schema.prototype.virtual. */ - constructor(options: Object, name: string); - /** Applies getters to value using optional scope. */ - applyGetters(value: Object, scope: Object): any; - /** Applies setters to value using optional scope. */ - applySetters(value: Object, scope: Object): any; - /** Defines a getter. */ - get(fn: Function): this; - /** Defines a setter. */ - set(fn: Function): this; - } - - /* - * section schema.js - * http://mongoosejs.com/docs/api.html#schema-js - */ - class Schema extends events.EventEmitter { - /** - * Schema constructor. - * When nesting schemas, (children in the example above), always declare - * the child schema first before passing it into its parent. - * @event init Emitted after the schema is compiled into a Model. - */ - constructor(definition?: Object, options?: SchemaOptions); - - /** Adds key path / schema type pairs to this schema. */ - add(obj: Object, prefix?: string): void; - - /** - * Iterates the schemas paths similar to Array.forEach. - * @param fn callback function - * @returns this - */ - eachPath(fn: (path: string, type: SchemaType) => void): this; - - /** - * Gets a schema option. - * @param key option name - */ - get(key: string): any; - - /** - * Defines an index (most likely compound) for this schema. - * @param options Options to pass to MongoDB driver's createIndex() function - * @param options.expires Mongoose-specific syntactic sugar, uses ms to convert - * expires option into seconds for the expireAfterSeconds in the above link. - */ - index(fields: Object, options?: { - expires?: string; - [other: string]: any; - }): this; - - /** Compiles indexes from fields and schema-level indexes */ - indexes(): any[]; - - /** - * Adds an instance method to documents constructed from Models compiled from this schema. - * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. - */ - method(method: string, fn: Function): this; - method(methodObj: { [name: string]: Function }): this; - - /** - * Gets/sets schema paths. - * Sets a path (if arity 2) - * Gets a path (if arity 1) - */ - path(path: string): SchemaType; - path(path: string, constructor: any): this; - - /** - * Returns the pathType of path for this schema. - * @returns whether it is a real, virtual, nested, or ad-hoc/undefined path. - */ - pathType(path: string): string; - - /** - * Registers a plugin for this schema. - * @param plugin callback - */ - plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this; - - /** - * Defines a post hook for the document - * Post hooks fire on the event emitted from document instances of Models compiled - * from this schema. - * @param method name of the method to hook - * @param fn callback - */ - post(method: string, fn: (doc: Model) => void, ...args: any[]): this; - post(method: string, fn: (doc: Model, next: (err?: NativeError) => void, - ...otherArgs: any[]) => void): this; - - /** - * Defines a pre hook for the document. - */ - pre(method: string, fn: (next: (err?: NativeError) => void) => void, - errorCb?: (err: Error) => void): this; - pre(method: string, parallel: boolean, fn: (next: (err?: NativeError) => void, done: () => void) => void, - errorCb?: (err: Error) => void): this; - - /** - * Adds a method call to the queue. - * @param name name of the document method to call later - * @param args arguments to pass to the method - */ - queue(name: string, args: any[]): this; - - /** - * Removes the given path (or [paths]). - */ - remove(path: string | string[]): void; - - /** - * @param invalidate refresh the cache - * @returns an Array of path strings that are required by this schema. - */ - requiredPaths(invalidate?: boolean): string[]; - - /** - * Sets/gets a schema option. - * @param key option name - * @param value if not passed, the current option value is returned - */ - set(key: string): any; - set(key: string, value: any): this; - - /** - * Adds static "class" methods to Models compiled from this schema. - */ - static(name: string, fn: Function): this; - static(nameObj: { [name: string]: Function }): this; - - /** Creates a virtual type with the given name. */ - virtual(name: string, options?: Object): VirtualType; - - /** Returns the virtual type with the given name. */ - virtualpath(name: string): VirtualType; - - /** The allowed index types */ - static indexTypes: string[]; - - /** - * Reserved document keys. - * Keys in this object are names that are rejected in schema declarations - * b/c they conflict with mongoose functionality. Using these key name - * will throw an error. - */ - static reserved: Object; - - static Types: { - Array: typeof _mongoose.Schema._Types.Array; - String: typeof _mongoose.Schema._Types.String; - DocumentArray: typeof _mongoose.Schema._Types.DocumentArray; - Number: typeof _mongoose.Schema._Types.Number; - Date: typeof _mongoose.Schema._Types.Date; - Buffer: typeof _mongoose.Schema._Types.Buffer; - Boolean: typeof _mongoose.Schema._Types.Boolean; - Bool: typeof _mongoose.Schema._Types.Boolean; - ObjectId: typeof _mongoose.Schema._Types.ObjectId; - Oid: typeof _mongoose.Schema._Types.ObjectId; - Mixed: typeof _mongoose.Schema._Types.Mixed; - Object: typeof _mongoose.Schema._Types.Mixed; - Embedded: typeof _mongoose.Schema._Types.Embedded; - } - - /** Object of currently defined methods on this schema. */ - methods: any; - /** Object of currently defined statics on this schema. */ - statics: any; - } - - interface SchemaOptions { - /** defaults to null (which means use the connection's autoIndex option) */ autoIndex?: boolean; - /** defaults to true */ - bufferCommands?: boolean; - /** defaults to false */ - capped?: boolean; - /** no default */ - collection?: string; - /** defaults to false. */ - emitIndexErrors?: boolean; - /** defaults to true */ - id?: boolean; - /** defaults to true */ - _id?: boolean; - /** controls document#toObject behavior when called manually - defaults to true */ - minimize?: boolean; - read?: string; - /** defaults to true. */ - safe?: boolean; - /** defaults to null */ - shardKey?: boolean; - /** defaults to true */ - strict?: boolean; - /** no default */ - toJSON?: Object; - /** no default */ - toObject?: Object; - /** defaults to 'type' */ - typeKey?: string; - /** defaults to false */ - useNestedStrict?: boolean; - /** defaults to true */ - validateBeforeSave?: boolean; - /** defaults to "__v" */ - versionKey?: boolean; + }; + } + + /** See the node-mongodb-native driver instance for options that it understands. */ + interface ConnectionOpenSetOptions extends ConnectionOptionsBase { + /** + * If true, enables High Availability support for mongos + * If connecting to multiple mongos servers, set the mongos option to true. + */ + mongos?: boolean; + } + + /* + * section drivers/node-mongodb-native/collection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js + */ + var Collection: Collection; + interface Collection extends CollectionBase { + /** + * Collection constructor + * @param name name of the collection + * @param conn A MongooseConnection instance + * @param opts optional collection options + */ + new(name: string, conn: Connection, opts?: Object): Collection; + /** Formatter for debug print args */ + $format(arg: any): string; + /** Debug print helper */ + $print(name: any, i: any, args: any[]): void; + /** Retreives information about this collections indexes. */ + getIndexes(): any; + } + + /* + * section drivers/node-mongodb-native/connection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js + */ + class Connection extends ConnectionBase { + /** + * Switches to a different database using the same connection pool. + * @param name The database name + * @returns New Connection Object + */ + useDb(name: string): Connection; + + /** Expose the possible connection states. */ + static STATES: Object; + } + + interface ConnectOptions extends ConnectionOpenOptions, ConnectionOpenSetOptions {} + + /* + * section error/validation.js + * http://mongoosejs.com/docs/api.html#error-validation-js + */ + class ValidationError extends Error { + /** Console.log helper */ + toString(): string; + } + + /* + * section error.js + * http://mongoosejs.com/docs/api.html#error-js + */ + class Error extends global.Error { + /** + * MongooseError constructor + * @param msg Error message + */ + constructor(msg: string); + + /** + * The default built-in validator error messages. These may be customized. + * As you might have noticed, error messages support basic templating + * {PATH} is replaced with the invalid document path + * {VALUE} is replaced with the invalid value + * {TYPE} is replaced with the validator type such as "regexp", "min", or "user defined" + * {MIN} is replaced with the declared min value for the Number.min validator + * {MAX} is replaced with the declared max value for the Number.max validator + */ + static messages: Object; + + /** For backwards compatibility. Same as mongoose.Error.messages */ + static Messages: Object; + } + + /* + * section querycursor.js + * http://mongoosejs.com/docs/api.html#querycursor-js + * + * Callback signatures are from: http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close + * QueryCursor can only be accessed by query#cursor(), we only + * expose its interface to enable type-checking. + */ + interface QueryCursor extends stream.Readable { + /** + * A QueryCursor is a concurrency primitive for processing query results + * one document at a time. A QueryCursor fulfills the Node.js streams3 API, + * in addition to several other mechanisms for loading documents from MongoDB + * one at a time. + * Unless you're an advanced user, do not instantiate this class directly. + * Use Query#cursor() instead. + * @param options query options passed to .find() + * @event cursor Emitted when the cursor is created + * @event error Emitted when an error occurred + * @event data Emitted when the stream is flowing and the next doc is ready + * @event end Emitted when the stream is exhausted + */ + constructor(query: Query, options: Object): QueryCursor; + + /** Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error. */ + close(callback?: (error: any, result: any) => void): _MongoosePromise; + + /** + * Execute fn for every document in the cursor. If fn returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + * @param callback executed when all docs have been processed + */ + eachAsync(fn: (doc: T) => any, callback?: (err: any) => void): _MongoosePromise; + + /** + * Get the next document from this cursor. Will return null when there are + * no documents left. + */ + next(callback?: (err: any) => void): _MongoosePromise; + } + + /* + * section virtualtype.js + * http://mongoosejs.com/docs/api.html#virtualtype-js + */ + class VirtualType { + /** This is what mongoose uses to define virtual attributes via Schema.prototype.virtual. */ + constructor(options: Object, name: string); + /** Applies getters to value using optional scope. */ + applyGetters(value: Object, scope: Object): any; + /** Applies setters to value using optional scope. */ + applySetters(value: Object, scope: Object): any; + /** Defines a getter. */ + get(fn: Function): this; + /** Defines a setter. */ + set(fn: Function): this; + } + + /* + * section schema.js + * http://mongoosejs.com/docs/api.html#schema-js + */ + class Schema extends events.EventEmitter { + /** + * Schema constructor. + * When nesting schemas, (children in the example above), always declare + * the child schema first before passing it into its parent. + * @event init Emitted after the schema is compiled into a Model. + */ + constructor(definition?: Object, options?: SchemaOptions); + + /** Adds key path / schema type pairs to this schema. */ + add(obj: Object, prefix?: string): void; + + /** + * Iterates the schemas paths similar to Array.forEach. + * @param fn callback function + * @returns this + */ + eachPath(fn: (path: string, type: SchemaType) => void): this; + + /** + * Gets a schema option. + * @param key option name + */ + get(key: string): any; + + /** + * Defines an index (most likely compound) for this schema. + * @param options Options to pass to MongoDB driver's createIndex() function + * @param options.expires Mongoose-specific syntactic sugar, uses ms to convert + * expires option into seconds for the expireAfterSeconds in the above link. + */ + index(fields: Object, options?: { + expires?: string; + [other: string]: any; + }): this; + + /** Compiles indexes from fields and schema-level indexes */ + indexes(): any[]; + + /** + * Adds an instance method to documents constructed from Models compiled from this schema. + * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. + */ + method(method: string, fn: Function): this; + method(methodObj: { [name: string]: Function }): this; + + /** + * Gets/sets schema paths. + * Sets a path (if arity 2) + * Gets a path (if arity 1) + */ + path(path: string): SchemaType; + path(path: string, constructor: any): this; + + /** + * Returns the pathType of path for this schema. + * @returns whether it is a real, virtual, nested, or ad-hoc/undefined path. + */ + pathType(path: string): string; + + /** + * Registers a plugin for this schema. + * @param plugin callback + */ + plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this; + + /** + * Defines a post hook for the document + * Post hooks fire on the event emitted from document instances of Models compiled + * from this schema. + * @param method name of the method to hook + * @param fn callback + */ + post(method: string, fn: (doc: T) => void, ...args: any[]): this; + post(method: string, fn: (doc: T, next: (err?: NativeError) => void, + ...otherArgs: any[]) => void): this; + + /** + * Defines a pre hook for the document. + */ + pre(method: string, fn: (next: (err?: NativeError) => void) => void, + errorCb?: (err: Error) => void): this; + pre(method: string, parallel: boolean, fn: (next: (err?: NativeError) => void, done: () => void) => void, + errorCb?: (err: Error) => void): this; + + /** + * Adds a method call to the queue. + * @param name name of the document method to call later + * @param args arguments to pass to the method + */ + queue(name: string, args: any[]): this; + + /** + * Removes the given path (or [paths]). + */ + remove(path: string | string[]): void; + + /** + * @param invalidate refresh the cache + * @returns an Array of path strings that are required by this schema. + */ + requiredPaths(invalidate?: boolean): string[]; + + /** + * Sets/gets a schema option. + * @param key option name + * @param value if not passed, the current option value is returned + */ + set(key: string): any; + set(key: string, value: any): this; + + /** + * Adds static "class" methods to Models compiled from this schema. + */ + static(name: string, fn: Function): this; + static(nameObj: { [name: string]: Function }): this; + + /** Creates a virtual type with the given name. */ + virtual(name: string, options?: Object): VirtualType; + + /** Returns the virtual type with the given name. */ + virtualpath(name: string): VirtualType; + + /** The allowed index types */ + static indexTypes: string[]; + + /** + * Reserved document keys. + * Keys in this object are names that are rejected in schema declarations + * b/c they conflict with mongoose functionality. Using these key name + * will throw an error. + */ + static reserved: Object; + + /** Object of currently defined methods on this schema. */ + methods: any; + /** Object of currently defined statics on this schema. */ + statics: any; + } + + interface SchemaOptions { + /** defaults to null (which means use the connection's autoIndex option) */ + autoIndex?: boolean; + /** defaults to true */ + bufferCommands?: boolean; + /** defaults to false */ + capped?: boolean; + /** no default */ + collection?: string; + /** defaults to false. */ + emitIndexErrors?: boolean; + /** defaults to true */ + id?: boolean; + /** defaults to true */ + _id?: boolean; + /** controls document#toObject behavior when called manually - defaults to true */ + minimize?: boolean; + read?: string; + /** defaults to true. */ + safe?: boolean; + /** defaults to null */ + shardKey?: boolean; + /** defaults to true */ + strict?: boolean; + /** no default */ + toJSON?: Object; + /** no default */ + toObject?: Object; + /** defaults to 'type' */ + typeKey?: string; + /** defaults to false */ + useNestedStrict?: boolean; + /** defaults to true */ + validateBeforeSave?: boolean; + /** defaults to "__v" */ + versionKey?: boolean; + /** + * skipVersioning allows excluding paths from + * versioning (the internal revision will not be + * incremented even if these paths are updated). + */ + skipVersioning?: Object; + /** + * If set timestamps, mongoose assigns createdAt + * and updatedAt fields to your schema, the type + * assigned is Date. + */ + timestamps?: Object; + } + + /* + * section document.js + * http://mongoosejs.com/docs/api.html#document-js + */ + class MongooseDocument { + /** Checks if a path is set to its default. */ + $isDefault(path?: string): boolean; + + /** + * Takes a populated field and returns it to its unpopulated state. + * If the path was not populated, this is a no-op. + */ + depopulate(path: string): void; + + /** + * Returns true if the Document stores the same data as doc. + * Documents are considered equal when they have matching _ids, unless neither document + * has an _id, in which case this function falls back to usin deepEqual(). + * @param doc a document to compare + */ + equals(doc: MongooseDocument): boolean; + + /** + * Explicitly executes population and returns a promise. + * Useful for ES2015 integration. + * @returns promise that resolves to the document when population is done + */ + execPopulate(): _MongoosePromise; + + /** + * Returns the value of a path. + * @param type optionally specify a type for on-the-fly attributes + */ + get(path: string, type?: any): any; + + /** + * Initializes the document without setters or marking anything modified. + * Called internally after a document is returned from mongodb. + * @param doc document returned by mongo + * @param fn callback + */ + init(doc: MongooseDocument, fn?: () => void): this; + init(doc: MongooseDocument, opts: Object, fn?: () => void): this; + + /** Helper for console.log */ + inspect(options?: Object): any; + + /** + * Marks a path as invalid, causing validation to fail. + * The errorMsg argument will become the message of the ValidationError. + * The value argument (if passed) will be available through the ValidationError.value property. + * @param path the field to invalidate + * @param errorMsg the error which states the reason path was invalid + * @param value optional invalid value + * @param kind optional kind property for the error + * @returns the current ValidationError, with all currently invalidated paths + */ + invalidate(path: string, errorMsg: string | NativeError, value: any, kind?: string): ValidationError | boolean; + + /** Returns true if path was directly set and modified, else false. */ + isDirectModified(path: string): boolean; + + /** Checks if path was initialized */ + isInit(path: string): boolean; + + /** + * Returns true if this document was modified, else false. + * If path is given, checks if a path or any full path containing path as part of its path + * chain has been modified. + */ + isModified(path?: string): boolean; + + /** Checks if path was selected in the source query which initialized this document. */ + isSelected(path: string): boolean; + + /** + * Marks the path as having pending changes to write to the db. + * Very helpful when using Mixed types. + * @param path the path to mark modified + */ + markModified(path: string): void; + + /** Returns the list of paths that have been modified. */ + modifiedPaths(): string[]; + + /** + * Populates document references, executing the callback when complete. + * If you want to use promises instead, use this function with + * execPopulate() + * Population does not occur unless a callback is passed or you explicitly + * call execPopulate(). Passing the same path a second time will overwrite + * the previous path options. See Model.populate() for explaination of options. + * @param path The path to populate or an options object + * @param callback When passed, population is invoked + */ + populate(callback: (err: any, res: this) => void): this; + populate(path: string, callback?: (err: any, res: this) => void): this; + populate(options: ModelPopulateOptions, callback?: (err: any, res: this) => void): this; + + /** Gets _id(s) used during population of the given path. If the path was not populated, undefined is returned. */ + populated(path: string): any; + + /** + * Sets the value of a path, or many paths. + * @param path path or object of key/vals to set + * @param val the value to set + * @param type optionally specify a type for "on-the-fly" attributes + * @param options optionally specify options that modify the behavior of the set + */ + set(path: string, val: any, options?: Object): void; + set(path: string, val: any, type: any, options?: Object): void; + set(value: Object): void; + + /** + * The return value of this method is used in calls to JSON.stringify(doc). + * This method accepts the same options as Document#toObject. To apply the + * options to every document of your schema by default, set your schemas + * toJSON option to the same argument. + */ + toJSON(options?: DocumentToObjectOptions): Object; + + /** + * Converts this document into a plain javascript object, ready for storage in MongoDB. + * Buffers are converted to instances of mongodb.Binary for proper storage. + */ + toObject(options?: DocumentToObjectOptions): Object; + + /** Helper for console.log */ + toString(): string; + + /** + * Clears the modified state on the specified path. + * @param path the path to unmark modified + */ + unmarkModified(path: string): void; + + /** Sends an update command with this document _id as the query selector. */ + update(doc: Object, callback?: (err: any, raw: any) => void): Query; + update(doc: Object, options: ModelUpdateOptions, + callback?: (err: any, raw: any) => void): Query; + + /** + * Executes registered validation rules for this document. + * @param optional options internal options + * @param callback callback called after validation completes, passing an error if one occurred + */ + validate(callback?: (err: any) => void): _MongoosePromise; + validate(optional: Object, callback?: (err: any) => void): _MongoosePromise; + + /** + * Executes registered validation rules (skipping asynchronous validators) for this document. + * This method is useful if you need synchronous validation. + * @param pathsToValidate only validate the given paths + * @returns MongooseError if there are errors during validation, or undefined if there is no error. + */ + validateSync(pathsToValidate: string | string[]): Error; + + /** Hash containing current validation errors. */ + errors: Object; + /** The string version of this documents _id. */ + id: string; + /** This documents _id. */ + _id: any; + /** Boolean flag specifying if the document is new. */ + isNew: boolean; + /** The documents schema. */ + schema: Schema; + } + + interface DocumentToObjectOptions { + /** apply all getters (path and virtual getters) */ + getters?: boolean; + /** apply virtual getters (can override getters option) */ + virtuals?: boolean; + /** remove empty objects (defaults to true) */ + minimize?: boolean; + /** + * A transform function to apply to the resulting document before returning + * @param doc The mongoose document which is being converted + * @param ret The plain object representation which has been converted + * @param options The options in use (either schema options or the options passed inline) + */ + transform?: (doc: any, ret: Object, options: Object) => any; + /** depopulate any populated paths, replacing them with their original refs (defaults to false) */ + depopulate?: boolean; + /** whether to include the version key (defaults to true) */ + versionKey?: boolean; + /** + * keep the order of object keys. If this is set to true, + * Object.keys(new Doc({ a: 1, b: 2}).toObject()) will + * always produce ['a', 'b'] (defaults to false) + */ + retainKeyOrder?: boolean; + } + + namespace Types { + /* + * section types/subdocument.js + * http://mongoosejs.com/docs/api.html#types-subdocument-js + */ + class Subdocument extends MongooseDocument { + /** Returns the top level document of this sub-document. */ + ownerDocument(): MongooseDocument; + /** - * skipVersioning allows excluding paths from - * versioning (the internal revision will not be - * incremented even if these paths are updated). + * Null-out this subdoc + * @param callback optional callback for compatibility with Document.prototype.remove */ - skipVersioning?: Object; - /** - * If set timestamps, mongoose assigns createdAt - * and updatedAt fields to your schema, the type - * assigned is Date. - */ - timestamps?: Object; + remove(callback?: (err: any) => void): void; + remove(options: Object, callback?: (err: any) => void): void; } /* - * section document.js - * http://mongoosejs.com/docs/api.html#document-js - */ - class Document { - /** Checks if a path is set to its default. */ - $isDefault(path?: string): boolean; + * section types/array.js + * http://mongoosejs.com/docs/api.html#types-array-js + */ + class Array extends global.Array { + /** + * Atomically shifts the array at most one time per document save(). + * Calling this mulitple times on an array before saving sends the same command as + * calling it once. This update is implemented using the MongoDB $pop method which + * enforces this restriction. + */ + $shift(): T; + + /** Alias of pull */ + remove(...args: any[]): this; /** - * Takes a populated field and returns it to its unpopulated state. - * If the path was not populated, this is a no-op. + * Pops the array atomically at most one time per document save(). + * Calling this mulitple times on an array before saving sends the same command as + * calling it once. This update is implemented using the MongoDB $pop method which + * enforces this restriction. */ - depopulate(path: string): void; + $pop(): T; /** - * Returns true if the Document stores the same data as doc. - * Documents are considered equal when they have matching _ids, unless neither document - * has an _id, in which case this function falls back to usin deepEqual(). - * @param doc a document to compare + * Adds values to the array if not already present. + * @returns the values that were added */ - equals(doc: Document): boolean; + addToSet(...args: any[]): T[]; /** - * Explicitly executes population and returns a promise. - * Useful for ES2015 integration. - * @returns promise that resolves to the document when population is done + * Return the index of obj or -1 if not found. + * @param obj he item to look for */ - execPopulate(): _MongoosePromise; - - /** - * Returns the value of a path. - * @param type optionally specify a type for on-the-fly attributes - */ - get(path: string, type?: any): any; - - /** - * Initializes the document without setters or marking anything modified. - * Called internally after a document is returned from mongodb. - * @param doc document returned by mongo - * @param fn callback - */ - init(doc: Document, fn?: () => void): this; - init(doc: Document, opts: Object, fn?: () => void): this; + indexOf(obj: any): number; /** Helper for console.log */ - inspect(options?: Object): any; + inspect(): any; + + /** + * Marks the entire array as modified, which if saved, will store it as a $set + * operation, potentially overwritting any changes that happen between when you + * retrieved the object and when you save it. + * @returns new length of the array + */ + nonAtomicPush(...args: any[]): number; + + /** + * Wraps Array#pop with proper change tracking. + * marks the entire array as modified which will pass the entire thing to $set + * potentially overwritting any changes that happen between when you retrieved + * the object and when you save it. + */ + pop(): T; + + /** + * Pulls items from the array atomically. Equality is determined by casting + * the provided value to an embedded document and comparing using + * the Document.equals() function. + */ + pull(...args: any[]): this; + + /** + * Wraps Array#push with proper change tracking. + * @returns new length of the array + */ + push(...args: any[]): number; + + /** Sets the casted val at index i and marks the array modified. */ + set(i: number, val: any): this; + + /** + * Wraps Array#shift with proper change tracking. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + shift(): T; + + /** + * Wraps Array#sort with proper change tracking. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + // some lib.d.ts have return type "this" and others have return type "T[]" + // which causes errors. Let the inherited array provide the sort() method. + //sort(compareFn?: (a: T, b: T) => number): T[]; + + /** + * Wraps Array#splice with proper change tracking and casting. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + splice(...args: any[]): T[]; + + /** Returns a native js Array. */ + toObject(options?: Object): T[]; + + /** + * Wraps Array#unshift with proper change tracking. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + unshift(...args: any[]): number; + } + + /* + * section types/documentarray.js + * http://mongoosejs.com/docs/api.html#types-documentarray-js + */ + class DocumentArray extends Types.Array { + /** + * Creates a subdocument casted to this schema. + * This is the same subdocument constructor used for casting. + * @param obj the value to cast to this arrays SubDocument schema + */ + create(obj: Object): Subdocument; + + /** + * Searches array items for the first document with a matching _id. + * @returns the subdocument or null if not found. + */ + id(id: ObjectId | string | number | NativeBuffer): Embedded; + + /** Helper for console.log */ + inspect(): T[]; + + /** + * Returns a native js Array of plain js objects + * @param options optional options to pass to each documents toObject + * method call during conversion + */ + toObject(options?: Object): T[]; + } + + /* + * section types/buffer.js + * http://mongoosejs.com/docs/api.html#types-buffer-js + */ + class Buffer extends global.Buffer { + /** + * Copies the buffer. + * Buffer#copy does not mark target as modified so you must copy + * from a MongooseBuffer for it to work as expected. This is a + * work around since copy modifies the target, not this. + */ + copy(target: NativeBuffer, ...nodeBufferArgs: any[]): number; + + /** Determines if this buffer is equals to other buffer */ + equals(other: NativeBuffer): boolean; + + /** Sets the subtype option and marks the buffer modified. */ + subtype(subtype: number): void; + + /** Converts this buffer to its Binary type representation. */ + toObject(subtype?: number): mongodb.Binary; + + /** Writes the buffer. */ + write(string: string, ...nodeBufferArgs: any[]): number; + } + + /* + * section types/objectid.js + * http://mongoosejs.com/docs/api.html#types-objectid-js + */ + var ObjectId: typeof mongodb.ObjectID; + interface ObjectId extends mongodb.ObjectID {} + + /* + * section types/embedded.js + * http://mongoosejs.com/docs/api.html#types-embedded-js + */ + class Embedded extends MongooseDocument { + /** Helper for console.log */ + inspect(): Object; /** * Marks a path as invalid, causing validation to fail. - * The errorMsg argument will become the message of the ValidationError. - * The value argument (if passed) will be available through the ValidationError.value property. * @param path the field to invalidate - * @param errorMsg the error which states the reason path was invalid - * @param value optional invalid value - * @param kind optional kind property for the error - * @returns the current ValidationError, with all currently invalidated paths + * @param err error which states the reason path was invalid */ - invalidate(path: string, errorMsg: string | NativeError, value: any, kind?: string): ValidationError | boolean; + invalidate(path: string, err: string | NativeError): boolean; - /** Returns true if path was directly set and modified, else false. */ - isDirectModified(path: string): boolean; + /** Returns the top level document of this sub-document. */ + ownerDocument(): MongooseDocument; + /** Returns this sub-documents parent document. */ + parent(): MongooseDocument; + /** Returns this sub-documents parent array. */ + parentArray(): DocumentArray; - /** Checks if path was initialized */ - isInit(path: string): boolean; + /** Removes the subdocument from its parent array. */ + remove(options?: { + noop?: boolean; + }, fn?: (err: any) => void): this; /** - * Returns true if this document was modified, else false. - * If path is given, checks if a path or any full path containing path as part of its path - * chain has been modified. - */ - isModified(path?: string): boolean; - - /** Checks if path was selected in the source query which initialized this document. */ - isSelected(path: string): boolean; - - /** - * Marks the path as having pending changes to write to the db. - * Very helpful when using Mixed types. - * @param path the path to mark modified + * Marks the embedded doc modified. + * @param path the path which changed */ markModified(path: string): void; - - /** Returns the list of paths that have been modified. */ - modifiedPaths(): string[]; - - /** - * Populates document references, executing the callback when complete. - * If you want to use promises instead, use this function with - * execPopulate() - * Population does not occur unless a callback is passed or you explicitly - * call execPopulate(). Passing the same path a second time will overwrite - * the previous path options. See Model.populate() for explaination of options. - * @param path The path to populate or an options object - * @param callback When passed, population is invoked - */ - populate(callback: (err: any, res: this) => void): this; - populate(path: string, callback?: (err: any, res: this) => void): this; - populate(options: ModelPopulateOptions, callback?: (err: any, res: this) => void): this; - - /** Gets _id(s) used during population of the given path. If the path was not populated, undefined is returned. */ - populated(path: string): any; - - /** - * Sets the value of a path, or many paths. - * @param path path or object of key/vals to set - * @param val the value to set - * @param type optionally specify a type for "on-the-fly" attributes - * @param options optionally specify options that modify the behavior of the set - */ - set(path: string, val: any, options?: Object): void; - set(path: string, val: any, type: any, options?: Object): void; - set(value: Object): void; - - /** - * The return value of this method is used in calls to JSON.stringify(doc). - * This method accepts the same options as Document#toObject. To apply the - * options to every document of your schema by default, set your schemas - * toJSON option to the same argument. - */ - toJSON(options?: DocumentToObjectOptions): Object; - - /** - * Converts this document into a plain javascript object, ready for storage in MongoDB. - * Buffers are converted to instances of mongodb.Binary for proper storage. - */ - toObject(options?: DocumentToObjectOptions): Object; - - /** Helper for console.log */ - toString(): string; - - /** - * Clears the modified state on the specified path. - * @param path the path to unmark modified - */ - unmarkModified(path: string): void; - - /** Sends an update command with this document _id as the query selector. */ - update(doc: Object, callback?: (err: any, raw: any) => void): Query; - update(doc: Object, options: ModelUpdateOptions, - callback?: (err: any, raw: any) => void): Query; - - /** - * Executes registered validation rules for this document. - * @param optional options internal options - * @param callback callback called after validation completes, passing an error if one occurred - */ - validate(callback?: (err: any) => void): _MongoosePromise; - validate(optional: Object, callback?: (err: any) => void): _MongoosePromise; - - /** - * Executes registered validation rules (skipping asynchronous validators) for this document. - * This method is useful if you need synchronous validation. - * @param pathsToValidate only validate the given paths - * @returns MongooseError if there are errors during validation, or undefined if there is no error. - */ - validateSync(pathsToValidate: string | string[]): _mongoose.Error; - - /** Hash containing current validation errors. */ - errors: Object; - /** The string version of this documents _id. */ - id: string; - /** This documents _id. */ - _id: any; - /** Boolean flag specifying if the document is new. */ - isNew: boolean; - /** The documents schema. */ - schema: Schema; } + } - interface DocumentToObjectOptions { - /** apply all getters (path and virtual getters) */ - getters?: boolean; - /** apply virtual getters (can override getters option) */ - virtuals?: boolean; - /** remove empty objects (defaults to true) */ - minimize?: boolean; - /** - * A transform function to apply to the resulting document before returning - * @param doc The mongoose document which is being converted - * @param ret The plain object representation which has been converted - * @param options The options in use (either schema options or the options passed inline) - */ - transform?: (doc: Model, ret: Object, options: Object) => any; - /** depopulate any populated paths, replacing them with their original refs (defaults to false) */ - depopulate?: boolean; - /** whether to include the version key (defaults to true) */ - versionKey?: boolean; - /** - * keep the order of object keys. If this is set to true, - * Object.keys(new Doc({ a: 1, b: 2}).toObject()) will - * always produce ['a', 'b'] (defaults to false) - */ - retainKeyOrder?: boolean; - } + /* + * section query.js + * http://mongoosejs.com/docs/api.html#query-js + */ + class Query extends ModelQuery {} - namespace Types { - /* - * section types/subdocument.js - * http://mongoosejs.com/docs/api.html#types-subdocument-js - */ - class Subdocument extends Document { - /** Returns the top level document of this sub-document. */ - ownerDocument(): Document; - - /** - * Null-out this subdoc - * @param callback optional callback for compatibility with Document.prototype.remove - */ - remove(callback?: (err: any) => void): void; - remove(options: Object, callback?: (err: any) => void): void; - } - - /* - * section types/array.js - * http://mongoosejs.com/docs/api.html#types-array-js - */ - class Array extends global.Array { - /** - * Atomically shifts the array at most one time per document save(). - * Calling this mulitple times on an array before saving sends the same command as - * calling it once. This update is implemented using the MongoDB $pop method which - * enforces this restriction. - */ - $shift(): T; - - /** Alias of pull */ - remove(...args: any[]): this; - - /** - * Pops the array atomically at most one time per document save(). - * Calling this mulitple times on an array before saving sends the same command as - * calling it once. This update is implemented using the MongoDB $pop method which - * enforces this restriction. - */ - $pop(): T; - - /** - * Adds values to the array if not already present. - * @returns the values that were added - */ - addToSet(...args: any[]): T[]; - - /** - * Return the index of obj or -1 if not found. - * @param obj he item to look for - */ - indexOf(obj: any): number; - - /** Helper for console.log */ - inspect(): any; - - /** - * Marks the entire array as modified, which if saved, will store it as a $set - * operation, potentially overwritting any changes that happen between when you - * retrieved the object and when you save it. - * @returns new length of the array - */ - nonAtomicPush(...args: any[]): number; - - /** - * Wraps Array#pop with proper change tracking. - * marks the entire array as modified which will pass the entire thing to $set - * potentially overwritting any changes that happen between when you retrieved - * the object and when you save it. - */ - pop(): T; - - /** - * Pulls items from the array atomically. Equality is determined by casting - * the provided value to an embedded document and comparing using - * the Document.equals() function. - */ - pull(...args: any[]): this; - - /** - * Wraps Array#push with proper change tracking. - * @returns new length of the array - */ - push(...args: any[]): number; - - /** Sets the casted val at index i and marks the array modified. */ - set(i: number, val: any): this; - - /** - * Wraps Array#shift with proper change tracking. - * Marks the entire array as modified, which if saved, will store it as a $set operation, - * potentially overwritting any changes that happen between when you retrieved the object - * and when you save it. - */ - shift(): T; - - /** - * Wraps Array#sort with proper change tracking. - * Marks the entire array as modified, which if saved, will store it as a $set operation, - * potentially overwritting any changes that happen between when you retrieved the object - * and when you save it. - */ - // some lib.d.ts have return type "this" and others have return type "T[]" - // which causes errors. Let the inherited array provide the sort() method. - //sort(compareFn?: (a: T, b: T) => number): T[]; - - /** - * Wraps Array#splice with proper change tracking and casting. - * Marks the entire array as modified, which if saved, will store it as a $set operation, - * potentially overwritting any changes that happen between when you retrieved the object - * and when you save it. - */ - splice(...args: any[]): T[]; - - /** Returns a native js Array. */ - toObject(options?: Object): T[]; - - /** - * Wraps Array#unshift with proper change tracking. - * Marks the entire array as modified, which if saved, will store it as a $set operation, - * potentially overwritting any changes that happen between when you retrieved the object - * and when you save it. - */ - unshift(...args: any[]): number; - } - - /* - * section types/documentarray.js - * http://mongoosejs.com/docs/api.html#types-documentarray-js - */ - class DocumentArray extends _mongoose.Types.Array { - /** - * Creates a subdocument casted to this schema. - * This is the same subdocument constructor used for casting. - * @param obj the value to cast to this arrays SubDocument schema - */ - create(obj: Object): Subdocument; - - /** - * Searches array items for the first document with a matching _id. - * @returns the subdocument or null if not found. - */ - id(id: ObjectId | string | number | NativeBuffer): Embedded; - - /** Helper for console.log */ - inspect(): T[]; - - /** - * Returns a native js Array of plain js objects - * @param options optional options to pass to each documents toObject - * method call during conversion - */ - toObject(options?: Object): T[]; - } - - /* - * section types/buffer.js - * http://mongoosejs.com/docs/api.html#types-buffer-js - */ - class Buffer extends global.Buffer { - /** - * Copies the buffer. - * Buffer#copy does not mark target as modified so you must copy - * from a MongooseBuffer for it to work as expected. This is a - * work around since copy modifies the target, not this. - */ - copy(target: NativeBuffer, ...nodeBufferArgs: any[]): number; - - /** Determines if this buffer is equals to other buffer */ - equals(other: NativeBuffer): boolean; - - /** Sets the subtype option and marks the buffer modified. */ - subtype(subtype: number): void; - - /** Converts this buffer to its Binary type representation. */ - toObject(subtype?: number): mongodb.Binary; - - /** Writes the buffer. */ - write(string: string, ...nodeBufferArgs: any[]): number; - } - - /* - * section types/objectid.js - * http://mongoosejs.com/docs/api.html#types-objectid-js - */ - var ObjectId: typeof mongodb.ObjectID; - interface ObjectId extends mongodb.ObjectID {} - - /* - * section types/embedded.js - * http://mongoosejs.com/docs/api.html#types-embedded-js - */ - class Embedded extends Document { - /** Helper for console.log */ - inspect(): Object; - - /** - * Marks a path as invalid, causing validation to fail. - * @param path the field to invalidate - * @param err error which states the reason path was invalid - */ - invalidate(path: string, err: string | NativeError): boolean; - - /** Returns the top level document of this sub-document. */ - ownerDocument(): Document; - /** Returns this sub-documents parent document. */ - parent(): Document; - /** Returns this sub-documents parent array. */ - parentArray(): DocumentArray; - - /** Removes the subdocument from its parent array. */ - remove(options?: { - noop?: boolean; - }, fn?: (err: any) => void): this; - - /** - * Marks the embedded doc modified. - * @param path the path which changed - */ - markModified(path: string): void; - } - } - - /* - * section query.js - * http://mongoosejs.com/docs/api.html#query-js + /* + * Query.find() will return Query[]> however we need the + * type T to create this so we save T in another parameter. + */ + class ModelQuery extends mquery { + /** + * Specifies a javascript function or expression to pass to MongoDBs query system. + * Only use $where when you have a condition that cannot be met using other MongoDB + * operators like $lt. Be sure to read about all of its caveats before using. + * @param js javascript string or function */ - type Query = ModelQuery; - - /* - * Query.find() will return Query[]> however we need the - * type T to create this so we save T in another parameter. - */ - class ModelQuery extends mquery { - /** - * Specifies a javascript function or expression to pass to MongoDBs query system. - * Only use $where when you have a condition that cannot be met using other MongoDB - * operators like $lt. Be sure to read about all of its caveats before using. - * @param js javascript string or function - */ - $where(js: string | Function): this; - - /** - * Specifies an $all query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - all(val: number): this; - all(path: string, val: number): this; - - /** - * Specifies arguments for a $and condition. - * @param array array of conditions - */ - and(array: Object[]): this; - - /** Specifies the batchSize option. Cannot be used with distinct() */ - batchSize(val: number): this; - - /** - * Specifies a $box condition - * @param Upper Right Coords - */ - box(val: Object): this; - box(lower: number[], upper: number[]): this; - - /** Casts this query to the schema of model, If obj is present, it is cast instead of this query.*/ - cast(model: Model | ModelConstructor, obj?: Object): Object; - - /** - * Executes the query returning a Promise which will be - * resolved with either the doc(s) or rejected with the error. - * Like .then(), but only takes a rejection handler. - */ - catch(reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise; - - /** - * DEPRECATED Alias for circle - * Specifies a $center or $centerSphere condition. - * @deprecated Use circle instead. - */ - center(area: Object): this; - center(path: string, area: Object): this; - - /** - * DEPRECATED Specifies a $centerSphere condition - * @deprecated Use circle instead. - */ - centerSphere(path: string, val: Object): this; - centerSphere(val: Object): this; - - /** Specifies a $center or $centerSphere condition. */ - circle(area: Object): this; - circle(path: string, area: Object): this; - - /** Specifies the comment option. Cannot be used with distinct() */ - comment(val: string): this; - - /** - * Specifying this query as a count query. Passing a callback executes the query. - * @param criteria mongodb selector - */ - count(callback?: (err: any, count: number) => void): Query; - count(criteria: Object, callback?: (err: any, count: number) => void): Query; - - /** - * Returns a wrapper around a mongodb driver cursor. A QueryCursor exposes a - * Streams3-compatible interface, as well as a .next() function. - */ - cursor(options?: Object): QueryCursor; - - /** Declares or executes a distict() operation. Passing a callback executes the query. */ - distinct(callback?: (err: any, res: any[]) => void): Query; - distinct(field: string, callback?: (err: any, res: any[]) => void): Query; - distinct(field: string, criteria: Object | Query, - callback?: (err: any, res: any[]) => void): Query; - - /** Specifies an $elemMatch condition */ - elemMatch(criteria: (elem: Query) => void): this; - elemMatch(criteria: Object): this; - elemMatch(path: string | Object | Function, criteria: (elem: Query) => void): this; - elemMatch(path: string | Object | Function, criteria: Object): this; - - /** Specifies the complementary comparison value for paths specified with where() */ - equals(val: Object): this; - - /** Executes the query */ - exec(callback?: (err: any, res: T) => void): _MongoosePromise; - exec(operation: string | Function, callback?: (err: any, res: T) => void): _MongoosePromise; - - /** Specifies an $exists condition */ - exists(val?: boolean): this; - exists(path: string, val?: boolean): this; - - /** - * Finds documents. When no callback is passed, the query is not executed. When the - * query is executed, the result will be an array of documents. - * @param criteria mongodb selector - */ - find(callback?: (err: any, res: Model[]) => void): ModelQuery[], ModelType>; - find(criteria: Object, - callback?: (err: any, res: Model[]) => void): ModelQuery[], ModelType>; - - /** - * Declares the query a findOne operation. When executed, the first found document is - * passed to the callback. Passing a callback executes the query. The result of the query - * is a single document. - * @param criteria mongodb selector - * @param projection optional fields to return - */ - findOne(callback?: (err: any, res: Model) => void): ModelQuery, ModelType>; - findOne(criteria: Object, - callback?: (err: any, res: Model) => void): ModelQuery, ModelType>; - - /** - * Issues a mongodb findAndModify remove command. - * Finds a matching document, removes it, passing the found document (if any) to the - * callback. Executes immediately if callback is passed. - */ - findOneAndRemove(callback?: (error: any, doc: Model, result: any) => void): ModelQuery, ModelType>; - findOneAndRemove(conditions: Object, - callback?: (error: any, doc: Model, result: any) => void): ModelQuery, ModelType>; - findOneAndRemove(conditions: Object, options: QueryFindOneAndRemoveOptions, - callback?: (error: any, doc: Model, result: any) => void): ModelQuery, ModelType>; - - /** - * Issues a mongodb findAndModify update command. - * Finds a matching document, updates it according to the update arg, passing any options, and returns - * the found document (if any) to the callback. The query executes immediately if callback is passed. - */ - findOneAndUpdate(callback?: (err: any, doc: Model) => void): ModelQuery, ModelType>; - findOneAndUpdate(update: Object, - callback?: (err: any, doc: Model) => void): ModelQuery, ModelType>; - findOneAndUpdate(query: Object | Query, update: Object, - callback?: (err: any, doc: Model) => void): ModelQuery, ModelType>; - findOneAndUpdate(query: Object | Query, update: Object, options: QueryFindOneAndUpdateOptions, - callback?: (err: any, doc: Model) => void): ModelQuery, ModelType>; - - /** - * Specifies a $geometry condition. geometry() must come after either intersects() or within(). - * @param object Must contain a type property which is a String and a coordinates property which - * is an Array. See the examples. - */ - geometry(object: { type: string, coordinates: any[] }): this; - - /** - * Returns the current query conditions as a JSON object. - * @returns current query conditions - */ - getQuery(): any; - - /** - * Returns the current update operations as a JSON object. - * @returns current update operations - */ - getUpdate(): any; - - /** - * Specifies a $gt query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - gt(val: number): this; - gt(path: string, val: number): this; - - /** - * Specifies a $gte query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - gte(val: number): this; - gte(path: string, val: number): this; - - /** - * Sets query hints. - * @param val a hint object - */ - hint(val: Object): this; - - /** - * Specifies an $in query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - in(val: any[]): this; - in(path: string, val: any[]): this; - - /** Declares an intersects query for geometry(). MUST be used after where(). */ - intersects(arg?: Object): this; - - /** - * Sets the lean option. - * Documents returned from queries with the lean option enabled are plain - * javascript objects, not MongooseDocuments. They have no save method, - * getters/setters or other Mongoose magic applied. - * @param bool defaults to true - */ - lean(bool?: boolean): Query; - - /** Specifies the maximum number of documents the query will return. Cannot be used with distinct() */ - limit(val: number): this; - - /** - * Specifies a $lt query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - lt(val: number): this; - lt(path: string, val: number): this; - - /** - * Specifies a $lte query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - lte(val: number): this; - lte(path: string, val: number): this; - - /** - * Specifies a $maxDistance query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - maxDistance(val: number): this; - maxDistance(path: string, val: number): this; - - /** @deprecated Alias of maxScan */ - maxscan(val: number): this; - /** Specifies the maxScan option. Cannot be used with distinct() */ - maxScan(val: number): this; - - /** - * Merges another Query or conditions object into this one. - * When a Query is passed, conditions, field selection and options are merged. - */ - merge(source: Object | Query): this; - - /** Specifies a $mod condition */ - mod(val: number[]): this; - mod(path: string, val: number[]): this; - - /** - * Specifies a $ne query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - ne(val: any): this; - ne(path: string, val: any): this; - - /** Specifies a $near or $nearSphere condition. */ - near(val: Object): this; - near(path: string, val: Object): this; - - /** - * DEPRECATED Specifies a $nearSphere condition - * @deprecated Use query.near() instead with the spherical option set to true. - */ - nearSphere(val: Object): this; - nearSphere(path: string, val: Object): this; - - /** - * Specifies a $nin query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - nin(val: any[]): this; - nin(path: string, val: any[]): this; - - /** - * Specifies arguments for a $nor condition. - * @param array array of conditions - */ - nor(array: Object[]): this; - - /** - * Specifies arguments for an $or condition. - * @param array array of conditions - */ - or(array: Object[]): this; - - /** Specifies a $polygon condition */ - polygon(...coordinatePairs: number[][]): this; - polygon(path: string, ...coordinatePairs: number[][]): this; - - /** - * Specifies paths which should be populated with other documents. - * Paths are populated after the query executes and a response is received. A separate - * query is then executed for each path specified for population. After a response for - * each query has also been returned, the results are passed to the callback. - * @param path either the path to populate or an object specifying all parameters - * @param select Field selection for the population query - * @param model The model you wish to use for population. If not specified, populate - * will look up the model by the name in the Schema's ref field. - * @param match Conditions for the population query - * @param options Options for the population query (sort, etc) - */ - populate(path: string | Object, select?: string | Object, model?: string | Model, - match?: Object, options?: Object): this; - populate(options: ModelPopulateOptions): this; - - /** - * Determines the MongoDB nodes from which to read. - * @param pref one of the listed preference options or aliases - * @tags optional tags for this query - */ - read(pref: string, tags?: Object[]): this; - - /** - * Specifies a $regex query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - regex(val: RegExp): this; - regex(path: string, val: RegExp): this; - - /** - * Declare and/or execute this query as a remove() operation. - * The operation is only executed when a callback is passed. To force execution without a callback, - * you must first call remove() and then execute it by using the exec() method. - * @param criteria mongodb selector - */ - remove(callback?: (err: any) => void): Query; - remove(criteria: Object | Query, callback?: (err: any) => void): Query; - - /** Specifies which document fields to include or exclude (also known as the query "projection") */ - select(arg: string | Object): this; - /** Determines if field selection has been made. */ - selected(): boolean; - /** Determines if exclusive field selection has been made.*/ - selectedExclusively(): boolean; - /** Determines if inclusive field selection has been made. */ - selectedInclusively(): boolean; - /** Sets query options. */ - setOptions(options: Object): this; - - /** - * Specifies a $size query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - size(val: number): this; - size(path: string, val: number): this; - - /** Specifies the number of documents to skip. Cannot be used with distinct() */ - skip(val: number): this; - - /** - * DEPRECATED Sets the slaveOk option. - * @param v defaults to true - * @deprecated in MongoDB 2.2 in favor of read preferences. - */ - slaveOk(v?: boolean): this; - - /** - * Specifies a $slice projection for an array. - * @param val number/range of elements to slice - */ - slice(val: number | number[]): this; - slice(path: string, val: number | number[]): this; - - /** Specifies this query as a snapshot query. Cannot be used with distinct() */ - snapshot(v?: boolean): this; - - /** - * Sets the sort order - * If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. - * If a string is passed, it must be a space delimited list of path names. The - * sort order of each path is ascending unless the path name is prefixed with - - * which will be treated as descending. - */ - sort(arg: string | Object): this; - - /** Returns a Node.js 0.8 style read stream interface. */ - stream(options?: { transform?: Function; }): QueryStream; - - /** - * Sets the tailable option (for use with capped collections). Cannot be used with distinct() - * @param bool defaults to true - * @param opts options to set - * @param opts.numberOfRetries if cursor is exhausted, retry this many times before giving up - * @param opts.tailableRetryInterval if cursor is exhausted, wait this many milliseconds before retrying - */ - tailable(bool?: boolean, opts?: { - numberOfRetries?: number; - tailableRetryInterval?: number; - }): this; - - /** Executes this query and returns a promise */ - then(resolve?: (res: T) => void | TRes | PromiseLike, - reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise; - - /** - * Converts this query to a customized, reusable query - * constructor with all arguments and options retained. - */ - toConstructor(): typeof ModelQuery; - - /** - * Declare and/or execute this query as an update() operation. - * All paths passed that are not $atomic operations will become $set ops. - * @param doc the update command - */ - update(callback?: (err: any, affectedRows: number) => void): Query; - update(doc: Object, callback?: (err: any, affectedRows: number) => void): Query; - update(criteria: Object, doc: Object, - callback?: (err: any, affectedRows: number) => void): Query; - update(criteria: Object, doc: Object, options: QueryUpdateOptions, - callback?: (err: any, affectedRows: number) => void): Query; - - /** Specifies a path for use with chaining. */ - where(path?: string | Object, val?: any): this; - - /** Defines a $within or $geoWithin argument for geo-spatial queries. */ - within(val?: Object): this; - within(coordinate: number[], ...coordinatePairs: number[][]): this; - - /** Flag to opt out of using $geoWithin. */ - static use$geoWithin: boolean; - } - - // https://github.com/aheckmann/mquery - // mquery currently does not have a type definition please - // replace it if one is ever created - class mquery {} - - interface QueryFindOneAndRemoveOptions { - /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ - sort?: any; - /** puts a time limit on the query - requires mongodb >= 2.6.0 */ - maxTimeMS?: number; - /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ - passRawResult?: boolean; - } - - interface QueryFindOneAndUpdateOptions extends QueryFindOneAndRemoveOptions { - /** if true, return the modified document rather than the original. defaults to false (changed in 4.0) */ - new?: boolean; - /** creates the object if it doesn't exist. defaults to false. */ - upsert?: boolean; - /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ - fields?: Object | string; - /** if true, runs update validators on this command. Update validators validate the update operation against the model's schema. */ - runValidators?: boolean; - /** - * if this and upsert are true, mongoose will apply the defaults specified in the model's schema if a new document - * is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB's $setOnInsert operator. - */ - setDefaultsOnInsert?: boolean; - /** - * if set to 'query' and runValidators is on, this will refer to the query in custom validator - * functions that update validation runs. Does nothing if runValidators is false. - */ - context?: string; - } - - interface QueryUpdateOptions extends ModelUpdateOptions { - /** - * if set to 'query' and runValidators is on, this will refer to the query - * in customvalidator functions that update validation runs. Does nothing - * if runValidators is false. - */ - context?: string; - } - - namespace Schema { - namespace _Types { - /* - * section schema/array.js - * http://mongoosejs.com/docs/api.html#schema-array-js - */ - class Array extends SchemaType { - /** Array SchemaType constructor */ - constructor(key: string, cast?: SchemaType, options?: Object); - - /** - * Check if the given value satisfies a required validator. The given value - * must be not null nor undefined, and have a non-zero length. - */ - checkRequired(value: T): boolean; - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - } - - /* - * section schema/string.js - * http://mongoosejs.com/docs/api.html#schema-string-js - */ - class String extends SchemaType { - /** String SchemaType constructor. */ - constructor(key: string, options?: Object); - - /** Check if the given value satisfies a required validator. */ - checkRequired(value: any, doc: Document): boolean; - - /** - * Adds an enum validator - * @param args enumeration values - */ - enum(args: string | string[] | Object): this; - - /** Adds a lowercase setter. */ - lowercase(): this; - - /** - * Sets a regexp validator. Any value that does not pass regExp.test(val) will fail validation. - * @param regExp regular expression to test against - * @param message optional custom error message - */ - match(regExp: RegExp, message?: string): this; - - /** - * Sets a maximum length validator. - * @param value maximum string length - * @param message optional custom error message - */ - maxlength(value: number, message?: string): this; - - /** - * Sets a minimum length validator. - * @param value minimum string length - * @param message optional custom error message - */ - minlength(value: number, message?: string): this; - - /** Adds a trim setter. The string value will be trimmed when set. */ - trim(): this; - /** Adds an uppercase setter. */ - uppercase(): this; - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - - } - - /* - * section schema/documentarray.js - * http://mongoosejs.com/docs/api.html#schema-documentarray-js - */ - class DocumentArray extends Array { - /** SubdocsArray SchemaType constructor */ - constructor(key: string, schema: Schema, options?: Object); - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - } - - /* - * section schema/number.js - * http://mongoosejs.com/docs/api.html#schema-number-js - */ - class Number extends SchemaType { - /** Number SchemaType constructor. */ - constructor(key: string, options?: Object); - - /** Check if the given value satisfies a required validator. */ - checkRequired(value: any, doc: Document): boolean; - - /** - * Sets a maximum number validator. - * @param maximum number - * @param message optional custom error message - */ - max(maximum: number, message?: string): this; - - /** - * Sets a minimum number validator. - * @param value minimum number - * @param message optional custom error message - */ - min(value: number, message?: string): this; - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - } - - /* - * section schema/date.js - * http://mongoosejs.com/docs/api.html#schema-date-js - */ - class Date extends SchemaType { - /** Date SchemaType constructor. */ - constructor(key: string, options?: Object); - - /** - * Check if the given value satisfies a required validator. To satisfy - * a required validator, the given value must be an instance of Date. - */ - checkRequired(value: any, doc: Document): boolean; - - /** Declares a TTL index (rounded to the nearest second) for Date types only. */ - expires(when: number | string): this; - - /** - * Sets a maximum date validator. - * @param maximum date - * @param message optional custom error message - */ - max(maximum: NativeDate, message?: string): this; - - /** - * Sets a minimum date validator. - * @param value minimum date - * @param message optional custom error message - */ - min(value: NativeDate, message?: string): this; - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - } - - /* - * section schema/buffer.js - * http://mongoosejs.com/docs/api.html#schema-buffer-js - */ - class Buffer extends SchemaType { - /** Buffer SchemaType constructor */ - constructor(key: string, options?: Object); - - /** - * Check if the given value satisfies a required validator. To satisfy a - * required validator, a buffer must not be null or undefined and have - * non-zero length. - */ - checkRequired(value: any, doc: Document): boolean; - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - - } - - /* - * section schema/boolean.js - * http://mongoosejs.com/docs/api.html#schema-boolean-js - */ - class Boolean extends SchemaType { - /** Boolean SchemaType constructor. */ - constructor(path: string, options?: Object); - - /** - * Check if the given value satisfies a required validator. For a - * boolean to satisfy a required validator, it must be strictly - * equal to true or to false. - */ - checkRequired(value: any): boolean; - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - } - - /* - * section schema/objectid.js - * http://mongoosejs.com/docs/api.html#schema-objectid-js - */ - class ObjectId extends SchemaType { - /** ObjectId SchemaType constructor. */ - constructor(key: string, options?: Object); - - /** - * Adds an auto-generated ObjectId default if turnOn is true. - * @param turnOn auto generated ObjectId defaults - */ - auto(turnOn: boolean): this; - - /** Check if the given value satisfies a required validator. */ - checkRequired(value: any, doc: Document): boolean; - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - } - - /* - * section schema/mixed.js - * http://mongoosejs.com/docs/api.html#schema-mixed-js - */ - class Mixed extends SchemaType { - /** Mixed SchemaType constructor. */ - constructor(path: string, options?: Object); - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - } - - /* - * section schema/embedded.js - * http://mongoosejs.com/docs/api.html#schema-embedded-js - */ - class Embedded extends SchemaType { - /** Sub-schema schematype constructor */ - constructor(schema: Schema, key: string, options?: Object); - } - } - } - - /* - * section aggregate.js - * http://mongoosejs.com/docs/api.html#aggregate-js - */ - class Aggregate { - /** - * Aggregate constructor used for building aggregation pipelines. - * Returned when calling Model.aggregate(). - * @param ops aggregation operator(s) or operator array - */ - constructor(ops?: Object | any[], ...args: any[]); - - /** Adds a cursor flag */ - addCursorFlag(flag: string, value: boolean): this; - - /** - * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) - * @param value Should tell server it can use hard drive to store data during aggregation. - * @param tags optional tags for this query - */ - allowDiskUse(value: boolean, tags?: any[]): this; - - /** - * Appends new operators to this aggregate pipeline - * @param ops operator(s) to append - */ - append(...ops: Object[]): this; - - /** - * Sets the cursor option option for the aggregation query (ignored for < 2.6.0). - * Note the different syntax below: .exec() returns a cursor object, and no callback - * is necessary. - * @param options set the cursor batch size - */ - cursor(options: Object): this; - - // If cursor option is on, could return an object - /** Executes the aggregate pipeline on the currently bound Model. */ - exec(callback?: (err: any, result: T) => void): _MongoosePromise | any; - - /** Execute the aggregation with explain */ - explain(callback?: (err: any, result: T) => void): _MongoosePromise; - - /** - * Appends a new custom $group operator to this aggregate pipeline. - * @param arg $group operator contents - */ - group(arg: Object): this; - - /** - * Appends a new $limit operator to this aggregate pipeline. - * @param num maximum number of records to pass to the next stage - */ - limit(num: number): this; - - /** - * Appends new custom $lookup operator(s) to this aggregate pipeline. - * @param options to $lookup as described in the above link - */ - lookup(options: Object): this; - - /** - * Appends a new custom $match operator to this aggregate pipeline. - * @param arg $match operator contents - */ - match(arg: Object): this; - - /** - * Binds this aggregate to a model. - * @param model the model to which the aggregate is to be bound - */ - model(model: Model): this; - - /** - * Appends a new $geoNear operator to this aggregate pipeline. - * MUST be used as the first operator in the pipeline. - */ - near(parameters: Object): this; - - /** - * Appends a new $project operator to this aggregate pipeline. - * Mongoose query selection syntax is also supported. - * @param arg field specification - */ - project(arg: string | Object): this; - - /** - * Sets the readPreference option for the aggregation query. - * @param pref one of the listed preference options or their aliases - * @param tags optional tags for this query - */ - read(pref: string, tags?: Object[]): this; - - /** - * Appends new custom $sample operator(s) to this aggregate pipeline. - * @param size number of random documents to pick - */ - sample(size: number): this; - - /** - * Appends a new $skip operator to this aggregate pipeline. - * @param num number of records to skip before next stage - */ - skip(num: number): this; - - /** - * Appends a new $sort operator to this aggregate pipeline. - * If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. - * If a string is passed, it must be a space delimited list of path names. The sort order - * of each path is ascending unless the path name is prefixed with - which will be treated - * as descending. - */ - sort(arg: string | Object): this; - - /** Provides promise for aggregate. */ - then(resolve?: (val: T) => void | TRes | PromiseLike, - reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise - - /** - * Appends new custom $unwind operator(s) to this aggregate pipeline. - * Note that the $unwind operator requires the path name to start with '$'. - * Mongoose will prepend '$' if the specified field doesn't start '$'. - * @param fields the field(s) to unwind - */ - unwind(...fields: string[]): this; - } - - /* - * section schematype.js - * http://mongoosejs.com/docs/api.html#schematype-js - */ - class SchemaType { - /** SchemaType constructor */ - constructor(path: string, options?: Object, instance?: string); - - /** - * Sets a default value for this SchemaType. - * Defaults can be either functions which return the value to use as the - * default or the literal value itself. Either way, the value will be cast - * based on its schema type before being set during document creation. - * @param val the default value - */ - default(val: any): any; - - /** Adds a getter to this schematype. */ - get(fn: Function): this; - - /** - * Declares the index options for this schematype. - * Indexes are created in the background by default. Specify background: false to override. - */ - index(options: Object | boolean | string): this; - - /** - * Adds a required validator to this SchemaType. The validator gets added - * to the front of this SchemaType's validators array using unshift(). - * @param required enable/disable the validator - * @param message optional custom error message - */ - required(required: boolean, message?: string): this; - - /** Sets default select() behavior for this path. */ - select(val: boolean): this; - /** Adds a setter to this schematype. */ - set(fn: Function): this; - /** Declares a sparse index. */ - sparse(bool: boolean): this; - /** Declares a full text index. */ - text(bool: boolean): this; - /** Declares an unique index. */ - unique(bool: boolean): this; - - /** - * Adds validator(s) for this document path. - * Validators always receive the value to validate as their first argument - * and must return Boolean. Returning false means validation failed. - * @param obj validator - * @param errorMsg optional error message - * @param type optional validator type - */ - validate(obj: RegExp | Function | Object, errorMsg?: string, - type?: string): this; - } + $where(js: string | Function): this; /** - * section promise.js - * http://mongoosejs.com/docs/api.html#promise-js - * - * You must assign a promise library: - * - * 1. To use mongoose's default promise library: - * Install mongoose-promise.d.ts - * - * 2. To use native ES6 promises, add this line to your main .d.ts file: - * type MongoosePromise = Promise; - * - * 3. To use another promise library (for example q): - * Install q.d.ts - * Then add this line to your main .d.ts file: - * type MongoosePromise = Q.Promise; + * Specifies an $all query condition. + * When called with one argument, the most recent path passed to where() is used. */ - type _MongoosePromise = MongoosePromise; + all(val: number): this; + all(path: string, val: number): this; - /* - * section model.js - * http://mongoosejs.com/docs/api.html#model-js - * - * Mongoose Models use multiple inheritance from Document and EventEmitter. - * When calling methods that return a model such as mongoose.connect(), - * they actual return an instance of the Model constructor (think of it - * like a new class) which can then instantiate its own objects. + /** + * Specifies arguments for a $and condition. + * @param array array of conditions */ - type ModelConstructor = IModelConstructor & events.EventEmitter; - type Model = T & _Model & events.EventEmitter; + and(array: Object[]): this; - interface IModelConstructor { - /** - * Model constructor - * Provides the interface to MongoDB collections as well as creates document instances. - * @param doc values with which to create the document - * @event error If listening to this event, it is emitted when a document - * was saved without passing a callback and an error occurred. If not - * listening, the event bubbles to the connection used to create this Model. - * @event index Emitted after Model#ensureIndexes completes. If an error - * occurred it is passed with the event. - * @event index-single-start Emitted when an individual index starts within - * Model#ensureIndexes. The fields and options being used to build the index - * are also passed with the event. - * @event index-single-done Emitted when an individual index finishes within - * Model#ensureIndexes. If an error occurred it is passed with the event. - * The fields, options, and index name are also passed. - */ - new(doc?: Object): Model; + /** Specifies the batchSize option. Cannot be used with distinct() */ + batchSize(val: number): this; - /** - * Finds a single document by its _id field. findById(id) is almost* - * equivalent to findOne({ _id: id }). findById() triggers findOne hooks. - * @param id value of _id to query by - * @param projection optional fields to return - */ - findById(id: Object | string | number, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findById(id: Object | string | number, projection: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findById(id: Object | string | number, projection: Object, options: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; + /** + * Specifies a $box condition + * @param Upper Right Coords + */ + box(val: Object): this; + box(lower: number[], upper: number[]): this; - model(name: string): ModelConstructor; - model(name: string): Statics & ModelConstructor; + /** Casts this query to the schema of model, If obj is present, it is cast instead of this query.*/ + cast(model: any, obj?: Object): Object; - /** - * Creates a Query and specifies a $where condition. - * @param argument is a javascript string or anonymous function - */ - $where(argument: string | Function): ModelQuery[], T>; + /** + * Executes the query returning a Promise which will be + * resolved with either the doc(s) or rejected with the error. + * Like .then(), but only takes a rejection handler. + */ + catch(reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise; - /** - * Performs aggregations on the models collection. - * If a callback is passed, the aggregate is executed and a Promise is returned. - * If a callback is not passed, the aggregate itself is returned. - * @param ... aggregation pipeline operator(s) or operator array - */ - aggregate(...aggregations: Object[]): Aggregate; - aggregate(...aggregationsWithCallback: Object[]): _MongoosePromise; + /** + * DEPRECATED Alias for circle + * Specifies a $center or $centerSphere condition. + * @deprecated Use circle instead. + */ + center(area: Object): this; + center(path: string, area: Object): this; - /** Counts number of matching documents in a database collection. */ - count(conditions: Object, callback?: (err: any, count: number) => void): Query; + /** + * DEPRECATED Specifies a $centerSphere condition + * @deprecated Use circle instead. + */ + centerSphere(path: string, val: Object): this; + centerSphere(val: Object): this; - /** - * Shortcut for saving one or more documents to the database. MyModel.create(docs) - * does new MyModel(doc).save() for every doc in docs. - * Triggers the save() hook. - */ - create(docs: any[], callback?: (err: any, res: Model[]) => void): _MongoosePromise[]>; - create(...docs: Object[]): _MongoosePromise>; - create(...docsWithCallback: Object[]): _MongoosePromise>; + /** Specifies a $center or $centerSphere condition. */ + circle(area: Object): this; + circle(path: string, area: Object): this; - /** - * Adds a discriminator type. - * @param name discriminator model name - * @param schema discriminator model schema - */ - discriminator(name: string, schema: Schema): Model; + /** Specifies the comment option. Cannot be used with distinct() */ + comment(val: string): this; - /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */ - distinct(field: string, callback?: (err: any, res: any[]) => void): Query; - distinct(field: string, conditions: Object, - callback?: (err: any, res: any[]) => void): Query; + /** + * Specifying this query as a count query. Passing a callback executes the query. + * @param criteria mongodb selector + */ + count(callback?: (err: any, count: number) => void): Query; + count(criteria: Object, callback?: (err: any, count: number) => void): Query; - /** - * Sends ensureIndex commands to mongo for each index declared in the schema. - * @param options internal options - * @param cb optional callback - */ - ensureIndexes(callback?: (err: any) => void): _MongoosePromise; - ensureIndexes(options: Object, callback?: (err: any) => void): _MongoosePromise; + /** + * Returns a wrapper around a mongodb driver cursor. A QueryCursor exposes a + * Streams3-compatible interface, as well as a .next() function. + */ + cursor(options?: Object): QueryCursor; - /** - * Finds documents. - * @param projection optional fields to return - */ - find(callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; - find(conditions: Object, callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; - find(conditions: Object, projection: Object, - callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; - find(conditions: Object, projection: Object, options: Object, - callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; + /** Declares or executes a distict() operation. Passing a callback executes the query. */ + distinct(callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, criteria: Object | Query, + callback?: (err: any, res: any[]) => void): Query; + /** Specifies an $elemMatch condition */ + elemMatch(criteria: (elem: Query) => void): this; + elemMatch(criteria: Object): this; + elemMatch(path: string | Object | Function, criteria: (elem: Query) => void): this; + elemMatch(path: string | Object | Function, criteria: Object): this; + /** Specifies the complementary comparison value for paths specified with where() */ + equals(val: Object): this; - /** - * Issue a mongodb findAndModify remove command by a document's _id field. - * findByIdAndRemove(id, ...) is equivalent to findOneAndRemove({ _id: id }, ...). - * Finds a matching document, removes it, passing the found document (if any) to the callback. - * Executes immediately if callback is passed, else a Query object is returned. - * @param id value of _id to query by - */ - findByIdAndRemove(): ModelQuery, T>; - findByIdAndRemove(id: Object | number | string, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findByIdAndRemove(id: Object | number | string, options: { - /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ - sort?: Object; - /** sets the document fields to return */ - select?: Object; - }, callback?: (err: any, res: Model) => void): ModelQuery, T>; + /** Executes the query */ + exec(callback?: (err: any, res: T) => void): _MongoosePromise; + exec(operation: string | Function, callback?: (err: any, res: T) => void): _MongoosePromise; - /** - * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) - * is equivalent to findOneAndUpdate({ _id: id }, ...). - * @param id value of _id to query by - */ - findByIdAndUpdate(): ModelQuery, T>; - findByIdAndUpdate(id: Object | number | string, update: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findByIdAndUpdate(id: Object | number | string, update: Object, - options: ModelFindByIdAndUpdateOptions, - callback?: (err: any, res: Model) => void): ModelQuery, T>; + /** Specifies an $exists condition */ + exists(val?: boolean): this; + exists(path: string, val?: boolean): this; - /** - * Finds one document. - * The conditions are cast to their respective SchemaTypes before the command is sent. - * @param projection optional fields to return - */ - findOne(conditions?: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findOne(conditions: Object, projection: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findOne(conditions: Object, projection: Object, options: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; + /** + * Finds documents. When no callback is passed, the query is not executed. When the + * query is executed, the result will be an array of documents. + * @param criteria mongodb selector + */ + find(callback?: (err: any, res: ModelType[]) => void): ModelQuery; + find(criteria: Object, + callback?: (err: any, res: ModelType[]) => void): ModelQuery; + + /** + * Declares the query a findOne operation. When executed, the first found document is + * passed to the callback. Passing a callback executes the query. The result of the query + * is a single document. + * @param criteria mongodb selector + * @param projection optional fields to return + */ + findOne(callback?: (err: any, res: ModelType) => void): ModelQuery; + findOne(criteria: Object, + callback?: (err: any, res: ModelType) => void): ModelQuery; + + /** + * Issues a mongodb findAndModify remove command. + * Finds a matching document, removes it, passing the found document (if any) to the + * callback. Executes immediately if callback is passed. + */ + findOneAndRemove(callback?: (error: any, doc: ModelType, result: any) => void): ModelQuery; + findOneAndRemove(conditions: Object, + callback?: (error: any, doc: ModelType, result: any) => void): ModelQuery; + findOneAndRemove(conditions: Object, options: QueryFindOneAndRemoveOptions, + callback?: (error: any, doc: ModelType, result: any) => void): ModelQuery; + + /** + * Issues a mongodb findAndModify update command. + * Finds a matching document, updates it according to the update arg, passing any options, and returns + * the found document (if any) to the callback. The query executes immediately if callback is passed. + */ + findOneAndUpdate(callback?: (err: any, doc: ModelType) => void): ModelQuery; + findOneAndUpdate(update: Object, + callback?: (err: any, doc: ModelType) => void): ModelQuery; + findOneAndUpdate(query: Object | Query, update: Object, + callback?: (err: any, doc: ModelType) => void): ModelQuery; + findOneAndUpdate(query: Object | Query, update: Object, options: QueryFindOneAndUpdateOptions, + callback?: (err: any, doc: ModelType) => void): ModelQuery; + + /** + * Specifies a $geometry condition. geometry() must come after either intersects() or within(). + * @param object Must contain a type property which is a String and a coordinates property which + * is an Array. See the examples. + */ + geometry(object: { type: string, coordinates: any[] }): this; + + /** + * Returns the current query conditions as a JSON object. + * @returns current query conditions + */ + getQuery(): any; + + /** + * Returns the current update operations as a JSON object. + * @returns current update operations + */ + getUpdate(): any; + + /** + * Specifies a $gt query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + gt(val: number): this; + gt(path: string, val: number): this; + + /** + * Specifies a $gte query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + gte(val: number): this; + gte(path: string, val: number): this; + + /** + * Sets query hints. + * @param val a hint object + */ + hint(val: Object): this; + + /** + * Specifies an $in query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + in(val: any[]): this; + in(path: string, val: any[]): this; + + /** Declares an intersects query for geometry(). MUST be used after where(). */ + intersects(arg?: Object): this; + + /** + * Sets the lean option. + * Documents returned from queries with the lean option enabled are plain + * javascript objects, not MongooseDocuments. They have no save method, + * getters/setters or other Mongoose magic applied. + * @param bool defaults to true + */ + lean(bool?: boolean): Query; + + /** Specifies the maximum number of documents the query will return. Cannot be used with distinct() */ + limit(val: number): this; + + /** + * Specifies a $lt query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + lt(val: number): this; + lt(path: string, val: number): this; + + /** + * Specifies a $lte query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + lte(val: number): this; + lte(path: string, val: number): this; + + /** + * Specifies a $maxDistance query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + maxDistance(val: number): this; + maxDistance(path: string, val: number): this; + + /** @deprecated Alias of maxScan */ + maxscan(val: number): this; + /** Specifies the maxScan option. Cannot be used with distinct() */ + maxScan(val: number): this; + + /** + * Merges another Query or conditions object into this one. + * When a Query is passed, conditions, field selection and options are merged. + */ + merge(source: Object | Query): this; + + /** Specifies a $mod condition */ + mod(val: number[]): this; + mod(path: string, val: number[]): this; + + /** + * Specifies a $ne query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + ne(val: any): this; + ne(path: string, val: any): this; + + /** Specifies a $near or $nearSphere condition. */ + near(val: Object): this; + near(path: string, val: Object): this; + + /** + * DEPRECATED Specifies a $nearSphere condition + * @deprecated Use query.near() instead with the spherical option set to true. + */ + nearSphere(val: Object): this; + nearSphere(path: string, val: Object): this; + + /** + * Specifies a $nin query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + nin(val: any[]): this; + nin(path: string, val: any[]): this; + + /** + * Specifies arguments for a $nor condition. + * @param array array of conditions + */ + nor(array: Object[]): this; + + /** + * Specifies arguments for an $or condition. + * @param array array of conditions + */ + or(array: Object[]): this; + + /** Specifies a $polygon condition */ + polygon(...coordinatePairs: number[][]): this; + polygon(path: string, ...coordinatePairs: number[][]): this; + + /** + * Specifies paths which should be populated with other documents. + * Paths are populated after the query executes and a response is received. A separate + * query is then executed for each path specified for population. After a response for + * each query has also been returned, the results are passed to the callback. + * @param path either the path to populate or an object specifying all parameters + * @param select Field selection for the population query + * @param model The model you wish to use for population. If not specified, populate + * will look up the model by the name in the Schema's ref field. + * @param match Conditions for the population query + * @param options Options for the population query (sort, etc) + */ + populate(path: string | Object, select?: string | Object, model?: any, + match?: Object, options?: Object): this; + populate(options: ModelPopulateOptions): this; + + /** + * Determines the MongoDB nodes from which to read. + * @param pref one of the listed preference options or aliases + * @tags optional tags for this query + */ + read(pref: string, tags?: Object[]): this; + + /** + * Specifies a $regex query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + regex(val: RegExp): this; + regex(path: string, val: RegExp): this; + + /** + * Declare and/or execute this query as a remove() operation. + * The operation is only executed when a callback is passed. To force execution without a callback, + * you must first call remove() and then execute it by using the exec() method. + * @param criteria mongodb selector + */ + remove(callback?: (err: any) => void): Query; + remove(criteria: Object | Query, callback?: (err: any) => void): Query; + + /** Specifies which document fields to include or exclude (also known as the query "projection") */ + select(arg: string | Object): this; + /** Determines if field selection has been made. */ + selected(): boolean; + /** Determines if exclusive field selection has been made.*/ + selectedExclusively(): boolean; + /** Determines if inclusive field selection has been made. */ + selectedInclusively(): boolean; + /** Sets query options. */ + setOptions(options: Object): this; + + /** + * Specifies a $size query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + size(val: number): this; + size(path: string, val: number): this; + + /** Specifies the number of documents to skip. Cannot be used with distinct() */ + skip(val: number): this; + + /** + * DEPRECATED Sets the slaveOk option. + * @param v defaults to true + * @deprecated in MongoDB 2.2 in favor of read preferences. + */ + slaveOk(v?: boolean): this; + + /** + * Specifies a $slice projection for an array. + * @param val number/range of elements to slice + */ + slice(val: number | number[]): this; + slice(path: string, val: number | number[]): this; + + /** Specifies this query as a snapshot query. Cannot be used with distinct() */ + snapshot(v?: boolean): this; + + /** + * Sets the sort order + * If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. + * If a string is passed, it must be a space delimited list of path names. The + * sort order of each path is ascending unless the path name is prefixed with - + * which will be treated as descending. + */ + sort(arg: string | Object): this; + + /** Returns a Node.js 0.8 style read stream interface. */ + stream(options?: { transform?: Function; }): QueryStream; + + /** + * Sets the tailable option (for use with capped collections). Cannot be used with distinct() + * @param bool defaults to true + * @param opts options to set + * @param opts.numberOfRetries if cursor is exhausted, retry this many times before giving up + * @param opts.tailableRetryInterval if cursor is exhausted, wait this many milliseconds before retrying + */ + tailable(bool?: boolean, opts?: { + numberOfRetries?: number; + tailableRetryInterval?: number; + }): this; + + /** Executes this query and returns a promise */ + then(resolve?: (res: T) => void | TRes | PromiseLike, + reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise; + + /** + * Converts this query to a customized, reusable query + * constructor with all arguments and options retained. + */ + toConstructor(): typeof ModelQuery; + + /** + * Declare and/or execute this query as an update() operation. + * All paths passed that are not $atomic operations will become $set ops. + * @param doc the update command + */ + update(callback?: (err: any, affectedRows: number) => void): Query; + update(doc: Object, callback?: (err: any, affectedRows: number) => void): Query; + update(criteria: Object, doc: Object, + callback?: (err: any, affectedRows: number) => void): Query; + update(criteria: Object, doc: Object, options: QueryUpdateOptions, + callback?: (err: any, affectedRows: number) => void): Query; + + /** Specifies a path for use with chaining. */ + where(path?: string | Object, val?: any): this; + + /** Defines a $within or $geoWithin argument for geo-spatial queries. */ + within(val?: Object): this; + within(coordinate: number[], ...coordinatePairs: number[][]): this; + + /** Flag to opt out of using $geoWithin. */ + static use$geoWithin: boolean; + } + + // https://github.com/aheckmann/mquery + // mquery currently does not have a type definition please + // replace it if one is ever created + class mquery {} + + interface QueryFindOneAndRemoveOptions { + /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ + sort?: any; + /** puts a time limit on the query - requires mongodb >= 2.6.0 */ + maxTimeMS?: number; + /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ + passRawResult?: boolean; + } + + interface QueryFindOneAndUpdateOptions extends QueryFindOneAndRemoveOptions { + /** if true, return the modified document rather than the original. defaults to false (changed in 4.0) */ + new?: boolean; + /** creates the object if it doesn't exist. defaults to false. */ + upsert?: boolean; + /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ + fields?: Object | string; + /** if true, runs update validators on this command. Update validators validate the update operation against the model's schema. */ + runValidators?: boolean; + /** + * if this and upsert are true, mongoose will apply the defaults specified in the model's schema if a new document + * is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB's $setOnInsert operator. + */ + setDefaultsOnInsert?: boolean; + /** + * if set to 'query' and runValidators is on, this will refer to the query in custom validator + * functions that update validation runs. Does nothing if runValidators is false. + */ + context?: string; + } + + interface QueryUpdateOptions extends ModelUpdateOptions { + /** + * if set to 'query' and runValidators is on, this will refer to the query + * in customvalidator functions that update validation runs. Does nothing + * if runValidators is false. + */ + context?: string; + } + + namespace Schema { + namespace Types { + /* + * section schema/array.js + * http://mongoosejs.com/docs/api.html#schema-array-js + */ + class Array extends SchemaType { + /** Array SchemaType constructor */ + constructor(key: string, cast?: SchemaType, options?: Object); - /** - * Issue a mongodb findAndModify remove command. - * Finds a matching document, removes it, passing the found document (if any) to the callback. - * Executes immediately if callback is passed else a Query object is returned. - */ - findOneAndRemove(): ModelQuery, T>; - findOneAndRemove(conditions: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findOneAndRemove(conditions: Object, options: { /** - * if multiple docs are found by the conditions, sets the sort order to choose - * which doc to update + * Check if the given value satisfies a required validator. The given value + * must be not null nor undefined, and have a non-zero length. */ - sort?: Object; - /** puts a time limit on the query - requires mongodb >= 2.6.0 */ - maxTimeMS?: number; - /** sets the document fields to return */ - select?: Object; - }, callback?: (err: any, res: Model) => void): ModelQuery, T>; + checkRequired(value: T): boolean; - /** - * Issues a mongodb findAndModify update command. - * Finds a matching document, updates it according to the update arg, passing any options, - * and returns the found document (if any) to the callback. The query executes immediately - * if callback is passed else a Query object is returned. - */ - findOneAndUpdate(): ModelQuery, T>; - findOneAndUpdate(conditions: Object, update: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findOneAndUpdate(conditions: Object, update: Object, - options: ModelFindOneAndUpdateOptions, - callback?: (err: any, res: Model) => void): ModelQuery, T>; + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } - /** - * geoNear support for Mongoose - * @param GeoJSON point or legacy coordinate pair [x,y] to search near - * @param options for the qurery - * @param callback optional callback for the query - */ - geoNear(point: number[] | { - type: string; - coordinates: number[] - }, options: { - /** return the raw object */ - lean?: boolean; - [other: string]: any; - }, callback?: (err: any, res: Model[], stats: any) => void): ModelQuery[], T>; + /* + * section schema/string.js + * http://mongoosejs.com/docs/api.html#schema-string-js + */ + class String extends SchemaType { + /** String SchemaType constructor. */ + constructor(key: string, options?: Object); - /** - * Implements $geoSearch functionality for Mongoose - * @param conditions an object that specifies the match condition (required) - * @param options for the geoSearch, some (near, maxDistance) are required - * @param callback optional callback - */ - geoSearch(conditions: Object, options: { - /** x,y point to search for */ - near: number[]; - /** the maximum distance from the point near that a result can be */ - maxDistance: number; - /** The maximum number of results to return */ - limit?: number; - /** return the raw object instead of the Mongoose Model */ - lean?: boolean; - }, callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; + /** Check if the given value satisfies a required validator. */ + checkRequired(value: any, doc: MongooseDocument): boolean; - /** - * Shortcut for creating a new Document from existing raw data, - * pre-saved in the DB. The document returned has no paths marked - * as modified initially. - */ - hydrate(obj: Object): Model; + /** + * Adds an enum validator + * @param args enumeration values + */ + enum(args: string | string[] | Object): this; - /** - * Shortcut for validating an array of documents and inserting them into - * MongoDB if they're all valid. This function is faster than .create() - * because it only sends one operation to the server, rather than one for each - * document. - * This function does not trigger save middleware. - */ - insertMany(docs: any[], callback?: (error: any, docs: Model[]) => void): _MongoosePromise[]>; - insertMany(doc: any, callback?: (error: any, doc: Model) => void): _MongoosePromise>; - insertMany(...docsWithCallback: Object[]): _MongoosePromise>; + /** Adds a lowercase setter. */ + lowercase(): this; - /** - * Executes a mapReduce command. - * @param o an object specifying map-reduce options - * @param callbackoptional callback - */ - mapReduce( - o: ModelMapReduceOption, Key, Value>, - callback?: (err: any, res: any) => void - ): _MongoosePromise; + /** + * Sets a regexp validator. Any value that does not pass regExp.test(val) will fail validation. + * @param regExp regular expression to test against + * @param message optional custom error message + */ + match(regExp: RegExp, message?: string): this; - /** - * Populates document references. - * @param docs Either a single document or array of documents to populate. - * @param options A hash of key/val (path, options) used for population. - * @param callback Optional callback, executed upon completion. Receives err and the doc(s). - */ - populate(docs: Object[], options: ModelPopulateOptions | ModelPopulateOptions[], - callback?: (err: any, res: Model[]) => void): _MongoosePromise[]>; - populate(docs: Object, options: ModelPopulateOptions | ModelPopulateOptions[], - callback?: (err: any, res: Model) => void): _MongoosePromise>; + /** + * Sets a maximum length validator. + * @param value maximum string length + * @param message optional custom error message + */ + maxlength(value: number, message?: string): this; - /** Removes documents from the collection. */ - remove(conditions: Object, callback?: (err: any) => void): Query; + /** + * Sets a minimum length validator. + * @param value minimum string length + * @param message optional custom error message + */ + minlength(value: number, message?: string): this; - /** - * Updates documents in the database without returning them. - * All update values are cast to their appropriate SchemaTypes before being sent. - */ - update(conditions: Object, doc: Object, - callback?: (err: any, raw: any) => void): Query; - update(conditions: Object, doc: Object, options: ModelUpdateOptions, - callback?: (err: any, raw: any) => void): Query; + /** Adds a trim setter. The string value will be trimmed when set. */ + trim(): this; + /** Adds an uppercase setter. */ + uppercase(): this; - /** Creates a Query, applies the passed conditions, and returns the Query. */ - where(path: string, val?: Object): Query; + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + } + + /* + * section schema/documentarray.js + * http://mongoosejs.com/docs/api.html#schema-documentarray-js + */ + class DocumentArray extends Array { + /** SubdocsArray SchemaType constructor */ + constructor(key: string, schema: Schema, options?: Object); + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/number.js + * http://mongoosejs.com/docs/api.html#schema-number-js + */ + class Number extends SchemaType { + /** Number SchemaType constructor. */ + constructor(key: string, options?: Object); + + /** Check if the given value satisfies a required validator. */ + checkRequired(value: any, doc: MongooseDocument): boolean; + + /** + * Sets a maximum number validator. + * @param maximum number + * @param message optional custom error message + */ + max(maximum: number, message?: string): this; + + /** + * Sets a minimum number validator. + * @param value minimum number + * @param message optional custom error message + */ + min(value: number, message?: string): this; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/date.js + * http://mongoosejs.com/docs/api.html#schema-date-js + */ + class Date extends SchemaType { + /** Date SchemaType constructor. */ + constructor(key: string, options?: Object); + + /** + * Check if the given value satisfies a required validator. To satisfy + * a required validator, the given value must be an instance of Date. + */ + checkRequired(value: any, doc: MongooseDocument): boolean; + + /** Declares a TTL index (rounded to the nearest second) for Date types only. */ + expires(when: number | string): this; + + /** + * Sets a maximum date validator. + * @param maximum date + * @param message optional custom error message + */ + max(maximum: NativeDate, message?: string): this; + + /** + * Sets a minimum date validator. + * @param value minimum date + * @param message optional custom error message + */ + min(value: NativeDate, message?: string): this; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/buffer.js + * http://mongoosejs.com/docs/api.html#schema-buffer-js + */ + class Buffer extends SchemaType { + /** Buffer SchemaType constructor */ + constructor(key: string, options?: Object); + + /** + * Check if the given value satisfies a required validator. To satisfy a + * required validator, a buffer must not be null or undefined and have + * non-zero length. + */ + checkRequired(value: any, doc: MongooseDocument): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + } + + /* + * section schema/boolean.js + * http://mongoosejs.com/docs/api.html#schema-boolean-js + */ + class Boolean extends SchemaType { + /** Boolean SchemaType constructor. */ + constructor(path: string, options?: Object); + + /** + * Check if the given value satisfies a required validator. For a + * boolean to satisfy a required validator, it must be strictly + * equal to true or to false. + */ + checkRequired(value: any): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/objectid.js + * http://mongoosejs.com/docs/api.html#schema-objectid-js + */ + class ObjectId extends SchemaType { + /** ObjectId SchemaType constructor. */ + constructor(key: string, options?: Object); + + /** + * Adds an auto-generated ObjectId default if turnOn is true. + * @param turnOn auto generated ObjectId defaults + */ + auto(turnOn: boolean): this; + + /** Check if the given value satisfies a required validator. */ + checkRequired(value: any, doc: MongooseDocument): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/mixed.js + * http://mongoosejs.com/docs/api.html#schema-mixed-js + */ + class Mixed extends SchemaType { + /** Mixed SchemaType constructor. */ + constructor(path: string, options?: Object); + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/embedded.js + * http://mongoosejs.com/docs/api.html#schema-embedded-js + */ + class Embedded extends SchemaType { + /** Sub-schema schematype constructor */ + constructor(schema: Schema, key: string, options?: Object); + } } + } - class _Model extends Document { - /** Signal that we desire an increment of this documents version. */ - increment(): this; + /* + * section aggregate.js + * http://mongoosejs.com/docs/api.html#aggregate-js + */ + class Aggregate { + /** + * Aggregate constructor used for building aggregation pipelines. + * Returned when calling Model.aggregate(). + * @param ops aggregation operator(s) or operator array + */ + constructor(ops?: Object | any[], ...args: any[]); - /** - * Returns another Model instance. - * @param name model name - */ - model(name: string): ModelConstructor; - model(name: string): Statics & ModelConstructor; + /** Adds a cursor flag */ + addCursorFlag(flag: string, value: boolean): this; - /** - * Removes this document from the db. - * @param fn optional callback - */ - remove(fn?: (err: any, product: Model) => void): _MongoosePromise>; + /** + * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) + * @param value Should tell server it can use hard drive to store data during aggregation. + * @param tags optional tags for this query + */ + allowDiskUse(value: boolean, tags?: any[]): this; - /** - * Saves this document. - * @param options options optional options - * @param options.safe overrides schema's safe option - * @param options.validateBeforeSave set to false to save without validating. - * @param fn optional callback - */ - save(fn?: (err: any, product: Model, numAffected: number) => void): _MongoosePromise>; + /** + * Appends new operators to this aggregate pipeline + * @param ops operator(s) to append + */ + append(...ops: Object[]): this; - /** Base Mongoose instance the model uses. */ - base: typeof mongoose; - /** - * If this is a discriminator model, baseModelName is the - * name of the base model. - */ - baseModelName: String; - /** Collection the model uses. */ - collection: Collection; - /** Connection the model uses. */ - db: Connection; - /** Registered discriminators for this model. */ - discriminators: any; - /** The name of the model */ - modelName: string; - /** Schema the model uses. */ - schema: Schema; - } + /** + * Sets the cursor option option for the aggregation query (ignored for < 2.6.0). + * Note the different syntax below: .exec() returns a cursor object, and no callback + * is necessary. + * @param options set the cursor batch size + */ + cursor(options: Object): this; - interface ModelFindByIdAndUpdateOptions { - /** true to return the modified document rather than the original. defaults to false */ - new?: boolean; - /** creates the object if it doesn't exist. defaults to false. */ - upsert?: boolean; - /** - * if true, runs update validators on this command. Update validators validate the - * update operation against the model's schema. - */ - runValidators?: boolean; - /** - * if this and upsert are true, mongoose will apply the defaults specified in the model's - * schema if a new document is created. This option only works on MongoDB >= 2.4 because - * it relies on MongoDB's $setOnInsert operator. - */ - setDefaultsOnInsert?: boolean; + // If cursor option is on, could return an object + /** Executes the aggregate pipeline on the currently bound Model. */ + exec(callback?: (err: any, result: T) => void): _MongoosePromise | any; + + /** Execute the aggregation with explain */ + explain(callback?: (err: any, result: T) => void): _MongoosePromise; + + /** + * Appends a new custom $group operator to this aggregate pipeline. + * @param arg $group operator contents + */ + group(arg: Object): this; + + /** + * Appends a new $limit operator to this aggregate pipeline. + * @param num maximum number of records to pass to the next stage + */ + limit(num: number): this; + + /** + * Appends new custom $lookup operator(s) to this aggregate pipeline. + * @param options to $lookup as described in the above link + */ + lookup(options: Object): this; + + /** + * Appends a new custom $match operator to this aggregate pipeline. + * @param arg $match operator contents + */ + match(arg: Object): this; + + /** + * Binds this aggregate to a model. + * @param model the model to which the aggregate is to be bound + */ + model(model: any): this; + + /** + * Appends a new $geoNear operator to this aggregate pipeline. + * MUST be used as the first operator in the pipeline. + */ + near(parameters: Object): this; + + /** + * Appends a new $project operator to this aggregate pipeline. + * Mongoose query selection syntax is also supported. + * @param arg field specification + */ + project(arg: string | Object): this; + + /** + * Sets the readPreference option for the aggregation query. + * @param pref one of the listed preference options or their aliases + * @param tags optional tags for this query + */ + read(pref: string, tags?: Object[]): this; + + /** + * Appends new custom $sample operator(s) to this aggregate pipeline. + * @param size number of random documents to pick + */ + sample(size: number): this; + + /** + * Appends a new $skip operator to this aggregate pipeline. + * @param num number of records to skip before next stage + */ + skip(num: number): this; + + /** + * Appends a new $sort operator to this aggregate pipeline. + * If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. + * If a string is passed, it must be a space delimited list of path names. The sort order + * of each path is ascending unless the path name is prefixed with - which will be treated + * as descending. + */ + sort(arg: string | Object): this; + + /** Provides promise for aggregate. */ + then(resolve?: (val: T) => void | TRes | PromiseLike, + reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise + + /** + * Appends new custom $unwind operator(s) to this aggregate pipeline. + * Note that the $unwind operator requires the path name to start with '$'. + * Mongoose will prepend '$' if the specified field doesn't start '$'. + * @param fields the field(s) to unwind + */ + unwind(...fields: string[]): this; + } + + /* + * section schematype.js + * http://mongoosejs.com/docs/api.html#schematype-js + */ + class SchemaType { + /** SchemaType constructor */ + constructor(path: string, options?: Object, instance?: string); + + /** + * Sets a default value for this SchemaType. + * Defaults can be either functions which return the value to use as the + * default or the literal value itself. Either way, the value will be cast + * based on its schema type before being set during document creation. + * @param val the default value + */ + default(val: any): any; + + /** Adds a getter to this schematype. */ + get(fn: Function): this; + + /** + * Declares the index options for this schematype. + * Indexes are created in the background by default. Specify background: false to override. + */ + index(options: Object | boolean | string): this; + + /** + * Adds a required validator to this SchemaType. The validator gets added + * to the front of this SchemaType's validators array using unshift(). + * @param required enable/disable the validator + * @param message optional custom error message + */ + required(required: boolean, message?: string): this; + + /** Sets default select() behavior for this path. */ + select(val: boolean): this; + /** Adds a setter to this schematype. */ + set(fn: Function): this; + /** Declares a sparse index. */ + sparse(bool: boolean): this; + /** Declares a full text index. */ + text(bool: boolean): this; + /** Declares an unique index. */ + unique(bool: boolean): this; + + /** + * Adds validator(s) for this document path. + * Validators always receive the value to validate as their first argument + * and must return Boolean. Returning false means validation failed. + * @param obj validator + * @param errorMsg optional error message + * @param type optional validator type + */ + validate(obj: RegExp | Function | Object, errorMsg?: string, + type?: string): this; + } + + /** + * section promise.js + * http://mongoosejs.com/docs/api.html#promise-js + * + * You must assign a promise library: + * + * 1. To use mongoose's default promise library: + * Install mongoose-promise.d.ts + * + * 2. To use native ES6 promises, add this line to your main .d.ts file: + * type MongoosePromise = Promise; + * + * 3. To use another promise library (for example q): + * Install q.d.ts + * Then add this line to your main .d.ts file: + * type MongoosePromise = Q.Promise; + */ + interface _MongoosePromise extends MongoosePromise {} + interface Promise extends MongoosePromise {} + + /** + * To assign your own promise library: + * + * 1. Include this somewhere in your code: + * mongoose.Promise = YOUR_PROMISE; + * + * 2. Include this somewhere in your main .d.ts file: + * type MongoosePromise = YOUR_PROMISE; + */ + export var Promise: any; + export var PromiseProvider: any; + + /* + * section model.js + * http://mongoosejs.com/docs/api.html#model-js + */ + interface Model extends NodeJS.EventEmitter { + /** + * Model constructor + * Provides the interface to MongoDB collections as well as creates document instances. + * @param doc values with which to create the document + * @event error If listening to this event, it is emitted when a document + * was saved without passing a callback and an error occurred. If not + * listening, the event bubbles to the connection used to create this Model. + * @event index Emitted after Model#ensureIndexes completes. If an error + * occurred it is passed with the event. + * @event index-single-start Emitted when an individual index starts within + * Model#ensureIndexes. The fields and options being used to build the index + * are also passed with the event. + * @event index-single-done Emitted when an individual index finishes within + * Model#ensureIndexes. If an error occurred it is passed with the event. + * The fields, options, and index name are also passed. + */ + new(doc?: Object): T; + + /** + * Finds a single document by its _id field. findById(id) is almost* + * equivalent to findOne({ _id: id }). findById() triggers findOne hooks. + * @param id value of _id to query by + * @param projection optional fields to return + */ + findById(id: Object | string | number, + callback?: (err: any, res: T) => void): ModelQuery; + findById(id: Object | string | number, projection: Object, + callback?: (err: any, res: T) => void): ModelQuery; + findById(id: Object | string | number, projection: Object, options: Object, + callback?: (err: any, res: T) => void): ModelQuery; + + model(name: string): Model; + + /** + * Creates a Query and specifies a $where condition. + * @param argument is a javascript string or anonymous function + */ + $where(argument: string | Function): ModelQuery; + + /** + * Performs aggregations on the models collection. + * If a callback is passed, the aggregate is executed and a Promise is returned. + * If a callback is not passed, the aggregate itself is returned. + * @param ... aggregation pipeline operator(s) or operator array + */ + aggregate(...aggregations: Object[]): Aggregate; + aggregate(...aggregationsWithCallback: Object[]): _MongoosePromise; + + /** Counts number of matching documents in a database collection. */ + count(conditions: Object, callback?: (err: any, count: number) => void): Query; + + /** + * Shortcut for saving one or more documents to the database. MyModel.create(docs) + * does new MyModel(doc).save() for every doc in docs. + * Triggers the save() hook. + */ + create(docs: any[], callback?: (err: any, res: T[]) => void): _MongoosePromise; + create(...docs: Object[]): _MongoosePromise; + create(...docsWithCallback: Object[]): _MongoosePromise; + + /** + * Adds a discriminator type. + * @param name discriminator model name + * @param schema discriminator model schema + */ + discriminator(name: string, schema: Schema): T; + + /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */ + distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, conditions: Object, + callback?: (err: any, res: any[]) => void): Query; + + /** + * Sends ensureIndex commands to mongo for each index declared in the schema. + * @param options internal options + * @param cb optional callback + */ + ensureIndexes(callback?: (err: any) => void): _MongoosePromise; + ensureIndexes(options: Object, callback?: (err: any) => void): _MongoosePromise; + + /** + * Finds documents. + * @param projection optional fields to return + */ + find(callback?: (err: any, res: T[]) => void): ModelQuery; + find(conditions: Object, callback?: (err: any, res: T[]) => void): ModelQuery; + find(conditions: Object, projection: Object, + callback?: (err: any, res: T[]) => void): ModelQuery; + find(conditions: Object, projection: Object, options: Object, + callback?: (err: any, res: T[]) => void): ModelQuery; + + + + /** + * Issue a mongodb findAndModify remove command by a document's _id field. + * findByIdAndRemove(id, ...) is equivalent to findOneAndRemove({ _id: id }, ...). + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * Executes immediately if callback is passed, else a Query object is returned. + * @param id value of _id to query by + */ + findByIdAndRemove(): ModelQuery; + findByIdAndRemove(id: Object | number | string, + callback?: (err: any, res: T) => void): ModelQuery; + findByIdAndRemove(id: Object | number | string, options: { /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ sort?: Object; /** sets the document fields to return */ select?: Object; - } + }, callback?: (err: any, res: T) => void): ModelQuery; - interface ModelFindOneAndUpdateOptions extends ModelFindByIdAndUpdateOptions { - /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ - fields?: Object | string; + /** + * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) + * is equivalent to findOneAndUpdate({ _id: id }, ...). + * @param id value of _id to query by + */ + findByIdAndUpdate(): ModelQuery; + findByIdAndUpdate(id: Object | number | string, update: Object, + callback?: (err: any, res: T) => void): ModelQuery; + findByIdAndUpdate(id: Object | number | string, update: Object, + options: ModelFindByIdAndUpdateOptions, + callback?: (err: any, res: T) => void): ModelQuery; + + /** + * Finds one document. + * The conditions are cast to their respective SchemaTypes before the command is sent. + * @param projection optional fields to return + */ + findOne(conditions?: Object, + callback?: (err: any, res: T) => void): ModelQuery; + findOne(conditions: Object, projection: Object, + callback?: (err: any, res: T) => void): ModelQuery; + findOne(conditions: Object, projection: Object, options: Object, + callback?: (err: any, res: T) => void): ModelQuery; + + /** + * Issue a mongodb findAndModify remove command. + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * Executes immediately if callback is passed else a Query object is returned. + */ + findOneAndRemove(): ModelQuery; + findOneAndRemove(conditions: Object, + callback?: (err: any, res: T) => void): ModelQuery; + findOneAndRemove(conditions: Object, options: { + /** + * if multiple docs are found by the conditions, sets the sort order to choose + * which doc to update + */ + sort?: Object; /** puts a time limit on the query - requires mongodb >= 2.6.0 */ maxTimeMS?: number; - /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ - passRawResult?: boolean; - } + /** sets the document fields to return */ + select?: Object; + }, callback?: (err: any, res: T) => void): ModelQuery; - interface ModelPopulateOptions { - /** space delimited path(s) to populate */ - path: string; - /** optional fields to select */ - select?: any; - /** optional query conditions to match */ - match?: Object; - /** optional name of the model to use for population */ - model?: string; - /** optional query options like sort, limit, etc */ - options?: Object; - } - - interface ModelUpdateOptions { - /** safe mode (defaults to value set in schema (true)) */ - safe?: boolean; - /** whether to create the doc if it doesn't match (false) */ - upsert?: boolean; - /** whether multiple documents should be updated (false) */ - multi?: boolean; - /** - * If true, runs update validators on this command. Update validators validate - * the update operation against the model's schema. - */ - runValidators?: boolean; - /** - * If this and upsert are true, mongoose will apply the defaults specified in the - * model's schema if a new document is created. This option only works on MongoDB >= 2.4 - * because it relies on MongoDB's $setOnInsert operator. - */ - setDefaultsOnInsert?: boolean; - /** overrides the strict option for this update */ - strict?: boolean; - /** disables update-only mode, allowing you to overwrite the doc (false) */ - overwrite?: boolean; - /** other options */ - [other: string]: any; - } - - interface ModelMapReduceOption { - map: Function | string; - reduce: (key: Key, vals: T[]) => Val; - /** query filter object. */ - query?: Object; - /** sort input objects using this key */ - sort?: Object; - /** max number of documents */ - limit?: number; - /** keep temporary data default: false */ - keeptemp?: boolean; - /** finalize function */ - finalize?: (key: Key, val: Val) => Val; - /** scope variables exposed to map/reduce/finalize during execution */ - scope?: Object; - /** it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X default: false */ - jsMode?: boolean; - /** provide statistics on job execution time. default: false */ - verbose?: boolean; - readPreference?: string; - /** sets the output target for the map reduce job. default: {inline: 1} */ - out?: { - /** the results are returned in an array */ - inline?: number; - /** - * {replace: 'collectionName'} add the results to collectionName: the - * results replace the collection - */ - replace?: string; - /** - * {reduce: 'collectionName'} add the results to collectionName: if - * dups are detected, uses the reducer / finalize functions - */ - reduce?: string; - /** - * {merge: 'collectionName'} add the results to collectionName: if - * dups exist the new docs overwrite the old - */ - merge?: string; - }; - } - - interface MapReduceResult { - _id: Key; - value: Val; - } - - /* - * section collection.js - * http://mongoosejs.com/docs/api.html#collection-js + /** + * Issues a mongodb findAndModify update command. + * Finds a matching document, updates it according to the update arg, passing any options, + * and returns the found document (if any) to the callback. The query executes immediately + * if callback is passed else a Query object is returned. */ - interface CollectionBase extends mongodb.Collection { - /* - * Abstract methods. Some of these are already defined on the - * mongodb.Collection interface so they've been commented out. - */ - ensureIndex(...args: any[]): any; - //find(...args: any[]): any; - findAndModify(...args: any[]): any; - //findOne(...args: any[]): any; - getIndexes(...args: any[]): any; - //insert(...args: any[]): any; - //mapReduce(...args: any[]): any; - //save(...args: any[]): any; - //update(...args: any[]): any; + findOneAndUpdate(): ModelQuery; + findOneAndUpdate(conditions: Object, update: Object, + callback?: (err: any, res: T) => void): ModelQuery; + findOneAndUpdate(conditions: Object, update: Object, + options: ModelFindOneAndUpdateOptions, + callback?: (err: any, res: T) => void): ModelQuery; - /** The collection name */ - collectionName: string; - /** The Connection instance */ - conn: Connection; - /** The collection name */ - name: string; - } + /** + * geoNear support for Mongoose + * @param GeoJSON point or legacy coordinate pair [x,y] to search near + * @param options for the qurery + * @param callback optional callback for the query + */ + geoNear(point: number[] | { + type: string; + coordinates: number[] + }, options: { + /** return the raw object */ + lean?: boolean; + [other: string]: any; + }, callback?: (err: any, res: T[], stats: any) => void): ModelQuery; + + /** + * Implements $geoSearch functionality for Mongoose + * @param conditions an object that specifies the match condition (required) + * @param options for the geoSearch, some (near, maxDistance) are required + * @param callback optional callback + */ + geoSearch(conditions: Object, options: { + /** x,y point to search for */ + near: number[]; + /** the maximum distance from the point near that a result can be */ + maxDistance: number; + /** The maximum number of results to return */ + limit?: number; + /** return the raw object instead of the Mongoose Model */ + lean?: boolean; + }, callback?: (err: any, res: T[]) => void): ModelQuery; + + /** + * Shortcut for creating a new Document from existing raw data, + * pre-saved in the DB. The document returned has no paths marked + * as modified initially. + */ + hydrate(obj: Object): T; + + /** + * Shortcut for validating an array of documents and inserting them into + * MongoDB if they're all valid. This function is faster than .create() + * because it only sends one operation to the server, rather than one for each + * document. + * This function does not trigger save middleware. + */ + insertMany(docs: any[], callback?: (error: any, docs: T[]) => void): _MongoosePromise; + insertMany(doc: any, callback?: (error: any, doc: T) => void): _MongoosePromise; + insertMany(...docsWithCallback: Object[]): _MongoosePromise; + + /** + * Executes a mapReduce command. + * @param o an object specifying map-reduce options + * @param callbackoptional callback + */ + mapReduce( + o: ModelMapReduceOption, + callback?: (err: any, res: any) => void + ): _MongoosePromise; + + /** + * Populates document references. + * @param docs Either a single document or array of documents to populate. + * @param options A hash of key/val (path, options) used for population. + * @param callback Optional callback, executed upon completion. Receives err and the doc(s). + */ + populate(docs: Object[], options: ModelPopulateOptions | ModelPopulateOptions[], + callback?: (err: any, res: T[]) => void): _MongoosePromise; + populate(docs: Object, options: ModelPopulateOptions | ModelPopulateOptions[], + callback?: (err: any, res: T) => void): _MongoosePromise; + + /** Removes documents from the collection. */ + remove(conditions: Object, callback?: (err: any) => void): Query; + + /** + * Updates documents in the database without returning them. + * All update values are cast to their appropriate SchemaTypes before being sent. + */ + update(conditions: Object, doc: Object, + callback?: (err: any, raw: any) => void): Query; + update(conditions: Object, doc: Object, options: ModelUpdateOptions, + callback?: (err: any, raw: any) => void): Query; + + /** Creates a Query, applies the passed conditions, and returns the Query. */ + where(path: string, val?: Object): Query; + } + + interface Document extends MongooseDocument, NodeJS.EventEmitter { + /** Signal that we desire an increment of this documents version. */ + increment(): this; + + /** + * Returns another Model instance. + * @param name model name + */ + model(name: string): Model; + + /** + * Removes this document from the db. + * @param fn optional callback + */ + remove(fn?: (err: any, product: T) => void): _MongoosePromise; + + /** + * Saves this document. + * @param options options optional options + * @param options.safe overrides schema's safe option + * @param options.validateBeforeSave set to false to save without validating. + * @param fn optional callback + */ + save(fn?: (err: any, product: T, numAffected: number) => void): _MongoosePromise; + + /** Base Mongoose instance the model uses. */ + base: typeof mongoose; + /** + * If this is a discriminator model, baseModelName is the + * name of the base model. + */ + baseModelName: String; + /** Collection the model uses. */ + collection: Collection; + /** Connection the model uses. */ + db: Connection; + /** Registered discriminators for this model. */ + discriminators: any; + /** The name of the model */ + modelName: string; + /** Schema the model uses. */ + schema: Schema; + } + + interface ModelFindByIdAndUpdateOptions { + /** true to return the modified document rather than the original. defaults to false */ + new?: boolean; + /** creates the object if it doesn't exist. defaults to false. */ + upsert?: boolean; + /** + * if true, runs update validators on this command. Update validators validate the + * update operation against the model's schema. + */ + runValidators?: boolean; + /** + * if this and upsert are true, mongoose will apply the defaults specified in the model's + * schema if a new document is created. This option only works on MongoDB >= 2.4 because + * it relies on MongoDB's $setOnInsert operator. + */ + setDefaultsOnInsert?: boolean; + /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ + sort?: Object; + /** sets the document fields to return */ + select?: Object; + } + + interface ModelFindOneAndUpdateOptions extends ModelFindByIdAndUpdateOptions { + /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ + fields?: Object | string; + /** puts a time limit on the query - requires mongodb >= 2.6.0 */ + maxTimeMS?: number; + /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ + passRawResult?: boolean; + } + + interface ModelPopulateOptions { + /** space delimited path(s) to populate */ + path: string; + /** optional fields to select */ + select?: any; + /** optional query conditions to match */ + match?: Object; + /** optional name of the model to use for population */ + model?: string; + /** optional query options like sort, limit, etc */ + options?: Object; + } + + interface ModelUpdateOptions { + /** safe mode (defaults to value set in schema (true)) */ + safe?: boolean; + /** whether to create the doc if it doesn't match (false) */ + upsert?: boolean; + /** whether multiple documents should be updated (false) */ + multi?: boolean; + /** + * If true, runs update validators on this command. Update validators validate + * the update operation against the model's schema. + */ + runValidators?: boolean; + /** + * If this and upsert are true, mongoose will apply the defaults specified in the + * model's schema if a new document is created. This option only works on MongoDB >= 2.4 + * because it relies on MongoDB's $setOnInsert operator. + */ + setDefaultsOnInsert?: boolean; + /** overrides the strict option for this update */ + strict?: boolean; + /** disables update-only mode, allowing you to overwrite the doc (false) */ + overwrite?: boolean; + /** other options */ + [other: string]: any; + } + + interface ModelMapReduceOption { + map: Function | string; + reduce: (key: Key, vals: T[]) => Val; + /** query filter object. */ + query?: Object; + /** sort input objects using this key */ + sort?: Object; + /** max number of documents */ + limit?: number; + /** keep temporary data default: false */ + keeptemp?: boolean; + /** finalize function */ + finalize?: (key: Key, val: Val) => Val; + /** scope variables exposed to map/reduce/finalize during execution */ + scope?: Object; + /** it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X default: false */ + jsMode?: boolean; + /** provide statistics on job execution time. default: false */ + verbose?: boolean; + readPreference?: string; + /** sets the output target for the map reduce job. default: {inline: 1} */ + out?: { + /** the results are returned in an array */ + inline?: number; + /** + * {replace: 'collectionName'} add the results to collectionName: the + * results replace the collection + */ + replace?: string; + /** + * {reduce: 'collectionName'} add the results to collectionName: if + * dups are detected, uses the reducer / finalize functions + */ + reduce?: string; + /** + * {merge: 'collectionName'} add the results to collectionName: if + * dups exist the new docs overwrite the old + */ + merge?: string; + }; + } + + interface MapReduceResult { + _id: Key; + value: Val; + } + + /* + * section collection.js + * http://mongoosejs.com/docs/api.html#collection-js + */ + interface CollectionBase extends mongodb.Collection { + /* + * Abstract methods. Some of these are already defined on the + * mongodb.Collection interface so they've been commented out. + */ + ensureIndex(...args: any[]): any; + //find(...args: any[]): any; + findAndModify(...args: any[]): any; + //findOne(...args: any[]): any; + getIndexes(...args: any[]): any; + //insert(...args: any[]): any; + //mapReduce(...args: any[]): any; + //save(...args: any[]): any; + //update(...args: any[]): any; + + /** The collection name */ + collectionName: string; + /** The Connection instance */ + conn: Connection; + /** The collection name */ + name: string; } } From 6f74da66624332e852e6ebffff3e1d944a6de907 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 7 Aug 2016 23:53:35 -0400 Subject: [PATCH 085/844] changed types of document.save() and remove() to this --- mongoose/mongoose.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 430b3a2b0c..1c18bc67f5 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2303,13 +2303,13 @@ declare module "mongoose" { * Returns another Model instance. * @param name model name */ - model(name: string): Model; + model(name: string): Model; /** * Removes this document from the db. * @param fn optional callback */ - remove(fn?: (err: any, product: T) => void): _MongoosePromise; + remove(fn?: (err: any, product: this) => void): _MongoosePromise; /** * Saves this document. @@ -2318,7 +2318,7 @@ declare module "mongoose" { * @param options.validateBeforeSave set to false to save without validating. * @param fn optional callback */ - save(fn?: (err: any, product: T, numAffected: number) => void): _MongoosePromise; + save(fn?: (err: any, product: this, numAffected: number) => void): _MongoosePromise; /** Base Mongoose instance the model uses. */ base: typeof mongoose; From c80cd0be05fb75bcc51f1c3b19f5ad0d451bc0f2 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 7 Aug 2016 23:56:11 -0400 Subject: [PATCH 086/844] changed ModelQuery to more accurate name DocumentQuery --- mongoose/mongoose.d.ts | 154 ++++++++++++++++++++--------------------- 1 file changed, 77 insertions(+), 77 deletions(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 1c18bc67f5..55bdd3393d 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -27,43 +27,43 @@ * is just a simple heuristic to keep track of our progress. * * TODO for version 4.x [updated][tested]: - * [x][ ] index.js - * [x][ ] querystream.js - * [x][ ] connection.js - * [x][ ] utils.js - * [x][ ] browser.js - * [x][ ] drivers/node-mongodb-native/collection.js - * [x][ ] drivers/node-mongodb-native/connection.js - * [x][ ] error/messages.js - * [x][ ] error/validation.js - * [x][ ] error.js - * [x][ ] querycursor.js - * [x][ ] virtualtype.js - * [x][ ] schema.js - * [x][ ] document.js - * [x][ ] types/subdocument.js - * [x][ ] types/array.js - * [x][ ] types/documentarray.js - * [x][ ] types/buffer.js - * [x][ ] types/objectid.js - * [x][ ] types/embedded.js - * [x][ ] query.js - * [x][ ] schema/array.js - * [x][ ] schema/string.js - * [x][ ] schema/documentarray.js - * [x][ ] schema/number.js - * [x][ ] schema/date.js - * [x][ ] schema/buffer.js - * [x][ ] schema/boolean.js - * [x][ ] schema/objectid.js - * [x][ ] schema/mixed.js - * [x][ ] schema/embedded.js - * [x][ ] aggregate.js - * [x][ ] schematype.js - * [x][ ] promise.js - * [x][ ] ES6Promise.js - * [x][ ] model.js - * [x][ ] collection.js + * [x][x] index.js + * [x][x] querystream.js + * [x][x] connection.js + * [x][x] utils.js + * [x][x] browser.js + * [x][x] drivers/node-mongodb-native/collection.js + * [x][x] drivers/node-mongodb-native/connection.js + * [x][x] error/messages.js + * [x][x] error/validation.js + * [x][x] error.js + * [x][x] querycursor.js + * [x][x] virtualtype.js + * [x][x] schema.js + * [x][x] document.js + * [x][x] types/subdocument.js + * [x][x] types/array.js + * [x][x] types/documentarray.js + * [x][x] types/buffer.js + * [x][x] types/objectid.js + * [x][x] types/embedded.js + * [x][x] query.js + * [x][x] schema/array.js + * [x][x] schema/string.js + * [x][x] schema/documentarray.js + * [x][x] schema/number.js + * [x][x] schema/date.js + * [x][x] schema/buffer.js + * [x][x] schema/boolean.js + * [x][x] schema/objectid.js + * [x][x] schema/mixed.js + * [x][x] schema/embedded.js + * [x][x] aggregate.js + * [x][x] schematype.js + * [x][x] promise.js + * [x][x] ES6Promise.js + * [x][x] model.js + * [x][x] collection.js */ /* @@ -1124,13 +1124,13 @@ declare module "mongoose" { * section query.js * http://mongoosejs.com/docs/api.html#query-js */ - class Query extends ModelQuery {} + class Query extends DocumentQuery {} /* * Query.find() will return Query[]> however we need the * type T to create this so we save T in another parameter. */ - class ModelQuery extends mquery { + class DocumentQuery extends mquery { /** * Specifies a javascript function or expression to pass to MongoDBs query system. * Only use $where when you have a condition that cannot be met using other MongoDB @@ -1205,7 +1205,7 @@ declare module "mongoose" { * Returns a wrapper around a mongodb driver cursor. A QueryCursor exposes a * Streams3-compatible interface, as well as a .next() function. */ - cursor(options?: Object): QueryCursor; + cursor(options?: Object): QueryCursor; /** Declares or executes a distict() operation. Passing a callback executes the query. */ distinct(callback?: (err: any, res: any[]) => void): Query; @@ -1235,9 +1235,9 @@ declare module "mongoose" { * query is executed, the result will be an array of documents. * @param criteria mongodb selector */ - find(callback?: (err: any, res: ModelType[]) => void): ModelQuery; + find(callback?: (err: any, res: DocType[]) => void): DocumentQuery; find(criteria: Object, - callback?: (err: any, res: ModelType[]) => void): ModelQuery; + callback?: (err: any, res: DocType[]) => void): DocumentQuery; /** * Declares the query a findOne operation. When executed, the first found document is @@ -1246,33 +1246,33 @@ declare module "mongoose" { * @param criteria mongodb selector * @param projection optional fields to return */ - findOne(callback?: (err: any, res: ModelType) => void): ModelQuery; + findOne(callback?: (err: any, res: DocType) => void): DocumentQuery; findOne(criteria: Object, - callback?: (err: any, res: ModelType) => void): ModelQuery; + callback?: (err: any, res: DocType) => void): DocumentQuery; /** * Issues a mongodb findAndModify remove command. * Finds a matching document, removes it, passing the found document (if any) to the * callback. Executes immediately if callback is passed. */ - findOneAndRemove(callback?: (error: any, doc: ModelType, result: any) => void): ModelQuery; + findOneAndRemove(callback?: (error: any, doc: DocType, result: any) => void): DocumentQuery; findOneAndRemove(conditions: Object, - callback?: (error: any, doc: ModelType, result: any) => void): ModelQuery; + callback?: (error: any, doc: DocType, result: any) => void): DocumentQuery; findOneAndRemove(conditions: Object, options: QueryFindOneAndRemoveOptions, - callback?: (error: any, doc: ModelType, result: any) => void): ModelQuery; + callback?: (error: any, doc: DocType, result: any) => void): DocumentQuery; /** * Issues a mongodb findAndModify update command. * Finds a matching document, updates it according to the update arg, passing any options, and returns * the found document (if any) to the callback. The query executes immediately if callback is passed. */ - findOneAndUpdate(callback?: (err: any, doc: ModelType) => void): ModelQuery; + findOneAndUpdate(callback?: (err: any, doc: DocType) => void): DocumentQuery; findOneAndUpdate(update: Object, - callback?: (err: any, doc: ModelType) => void): ModelQuery; + callback?: (err: any, doc: DocType) => void): DocumentQuery; findOneAndUpdate(query: Object | Query, update: Object, - callback?: (err: any, doc: ModelType) => void): ModelQuery; + callback?: (err: any, doc: DocType) => void): DocumentQuery; findOneAndUpdate(query: Object | Query, update: Object, options: QueryFindOneAndUpdateOptions, - callback?: (err: any, doc: ModelType) => void): ModelQuery; + callback?: (err: any, doc: DocType) => void): DocumentQuery; /** * Specifies a $geometry condition. geometry() must come after either intersects() or within(). @@ -1521,7 +1521,7 @@ declare module "mongoose" { * Converts this query to a customized, reusable query * constructor with all arguments and options retained. */ - toConstructor(): typeof ModelQuery; + toConstructor(): typeof DocumentQuery; /** * Declare and/or execute this query as an update() operation. @@ -2066,11 +2066,11 @@ declare module "mongoose" { * @param projection optional fields to return */ findById(id: Object | string | number, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findById(id: Object | string | number, projection: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findById(id: Object | string | number, projection: Object, options: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; model(name: string): Model; @@ -2078,7 +2078,7 @@ declare module "mongoose" { * Creates a Query and specifies a $where condition. * @param argument is a javascript string or anonymous function */ - $where(argument: string | Function): ModelQuery; + $where(argument: string | Function): DocumentQuery; /** * Performs aggregations on the models collection. @@ -2125,12 +2125,12 @@ declare module "mongoose" { * Finds documents. * @param projection optional fields to return */ - find(callback?: (err: any, res: T[]) => void): ModelQuery; - find(conditions: Object, callback?: (err: any, res: T[]) => void): ModelQuery; + find(callback?: (err: any, res: T[]) => void): DocumentQuery; + find(conditions: Object, callback?: (err: any, res: T[]) => void): DocumentQuery; find(conditions: Object, projection: Object, - callback?: (err: any, res: T[]) => void): ModelQuery; + callback?: (err: any, res: T[]) => void): DocumentQuery; find(conditions: Object, projection: Object, options: Object, - callback?: (err: any, res: T[]) => void): ModelQuery; + callback?: (err: any, res: T[]) => void): DocumentQuery; @@ -2141,27 +2141,27 @@ declare module "mongoose" { * Executes immediately if callback is passed, else a Query object is returned. * @param id value of _id to query by */ - findByIdAndRemove(): ModelQuery; + findByIdAndRemove(): DocumentQuery; findByIdAndRemove(id: Object | number | string, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findByIdAndRemove(id: Object | number | string, options: { /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ sort?: Object; /** sets the document fields to return */ select?: Object; - }, callback?: (err: any, res: T) => void): ModelQuery; + }, callback?: (err: any, res: T) => void): DocumentQuery; /** * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) * is equivalent to findOneAndUpdate({ _id: id }, ...). * @param id value of _id to query by */ - findByIdAndUpdate(): ModelQuery; + findByIdAndUpdate(): DocumentQuery; findByIdAndUpdate(id: Object | number | string, update: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findByIdAndUpdate(id: Object | number | string, update: Object, options: ModelFindByIdAndUpdateOptions, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; /** * Finds one document. @@ -2169,20 +2169,20 @@ declare module "mongoose" { * @param projection optional fields to return */ findOne(conditions?: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findOne(conditions: Object, projection: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findOne(conditions: Object, projection: Object, options: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; /** * Issue a mongodb findAndModify remove command. * Finds a matching document, removes it, passing the found document (if any) to the callback. * Executes immediately if callback is passed else a Query object is returned. */ - findOneAndRemove(): ModelQuery; + findOneAndRemove(): DocumentQuery; findOneAndRemove(conditions: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findOneAndRemove(conditions: Object, options: { /** * if multiple docs are found by the conditions, sets the sort order to choose @@ -2193,7 +2193,7 @@ declare module "mongoose" { maxTimeMS?: number; /** sets the document fields to return */ select?: Object; - }, callback?: (err: any, res: T) => void): ModelQuery; + }, callback?: (err: any, res: T) => void): DocumentQuery; /** * Issues a mongodb findAndModify update command. @@ -2201,12 +2201,12 @@ declare module "mongoose" { * and returns the found document (if any) to the callback. The query executes immediately * if callback is passed else a Query object is returned. */ - findOneAndUpdate(): ModelQuery; + findOneAndUpdate(): DocumentQuery; findOneAndUpdate(conditions: Object, update: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findOneAndUpdate(conditions: Object, update: Object, options: ModelFindOneAndUpdateOptions, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; /** * geoNear support for Mongoose @@ -2221,7 +2221,7 @@ declare module "mongoose" { /** return the raw object */ lean?: boolean; [other: string]: any; - }, callback?: (err: any, res: T[], stats: any) => void): ModelQuery; + }, callback?: (err: any, res: T[], stats: any) => void): DocumentQuery; /** * Implements $geoSearch functionality for Mongoose @@ -2238,7 +2238,7 @@ declare module "mongoose" { limit?: number; /** return the raw object instead of the Mongoose Model */ lean?: boolean; - }, callback?: (err: any, res: T[]) => void): ModelQuery; + }, callback?: (err: any, res: T[]) => void): DocumentQuery; /** * Shortcut for creating a new Document from existing raw data, From bbce379d500ae7687d647bec3c4c47b238b5cac1 Mon Sep 17 00:00:00 2001 From: Simon Date: Mon, 8 Aug 2016 00:00:35 -0400 Subject: [PATCH 087/844] updated tests for extending mongoose.Document and mongoose.Model --- mongoose/mongoose-tests.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 12d84cef3e..2b00e665cd 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1355,9 +1355,19 @@ interface MyModel extends mongoose.Model { staticMethod: () => void; } interface ModelStruct { - doc: MyDocument, - model: MyModel + doc: MyDocument; + model: MyModel; + method1: (callback: (model: MyModel, doc: MyDocument) => void) => MyModel; } +var modelStruct1: ModelStruct; +var myModel1: MyModel; +var myDocument1: MyDocument; +modelStruct1.method1(function (myModel1, myDocument1) { + myModel1.staticProp; + myModel1.staticMethod(); + myDocument1.prop; + myDocument1.method(); +}).staticProp.toLowerCase(); var mySchema = new mongoose.Schema({}); export var Final: MyModel = mongoose.connection.model('Final', mySchema); Final.findOne(function (err: any, doc: MyDocument) { From 11b67e8ad3366c45905034ea6079a62b1b4d54b0 Mon Sep 17 00:00:00 2001 From: Louy Alakkad Date: Tue, 9 Aug 2016 21:22:15 +0100 Subject: [PATCH 088/844] Return value of DocumentQuery#remove --- mongoose/mongoose.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 55bdd3393d..45c218a94c 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -1448,8 +1448,8 @@ declare module "mongoose" { * you must first call remove() and then execute it by using the exec() method. * @param criteria mongodb selector */ - remove(callback?: (err: any) => void): Query; - remove(criteria: Object | Query, callback?: (err: any) => void): Query; + remove(callback?: (err: any) => void): Query; + remove(criteria: Object | Query, callback?: (err: any) => void): Query; /** Specifies which document fields to include or exclude (also known as the query "projection") */ select(arg: string | Object): this; From 6d2d24d72a5bb5dce3cd39c707028c2ba2d3485e Mon Sep 17 00:00:00 2001 From: Louy Alakkad Date: Tue, 9 Aug 2016 21:03:19 +0100 Subject: [PATCH 089/844] Adding Model.modelName and Model.collection See: https://github.com/Automattic/mongoose/blob/5c490f99e5d281e5303c023bade93a0624e5db66/lib/model.js#L62-L88 --- mongoose/mongoose.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 45c218a94c..3b6590feda 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2059,6 +2059,15 @@ declare module "mongoose" { */ new(doc?: Object): T; + /** The name of the model. */ + modelName: string; + + /** Collection the model uses. */ + collection: Collection; + + /** If this is a discriminator model, `baseModelName` is the name of the base model. */ + baseModelName: string; + /** * Finds a single document by its _id field. findById(id) is almost* * equivalent to findOne({ _id: id }). findById() triggers findOne hooks. From a2158341d855bf1aa8b1d80e282f67d864596b0e Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 14 Aug 2016 23:53:38 -0400 Subject: [PATCH 090/844] moved properties of Model and model into a separate interface --- mongoose/mongoose-tests.ts | 4 ++++ mongoose/mongoose.d.ts | 32 ++++++++++++++++++++++++++------ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 2b00e665cd..ddec97e9d1 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1249,6 +1249,10 @@ mongoModel.discriminators; mongoModel.modelName.toLowerCase(); MongoModel = mongoModel.base.model('new', mongoModel.schema); /* inherited properties */ +MongoModel.modelName; +mongoModel.modelName; +MongoModel.collection; +mongoModel.collection; mongoModel._id; mongoModel.execPopulate(); mongoModel.on('data', cb); diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 3b6590feda..a6a2fc409c 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2040,7 +2040,7 @@ declare module "mongoose" { * section model.js * http://mongoosejs.com/docs/api.html#model-js */ - interface Model extends NodeJS.EventEmitter { + interface Model extends NodeJS.EventEmitter, ModelProperties { /** * Model constructor * Provides the interface to MongoDB collections as well as creates document instances. @@ -2059,14 +2059,26 @@ declare module "mongoose" { */ new(doc?: Object): T; - /** The name of the model. */ - modelName: string; + /** Base Mongoose instance the model uses. */ + base: typeof mongoose; + + /** If this is a discriminator model, `baseModelName` is the name of the base model. */ + baseModelName: string; /** Collection the model uses. */ collection: Collection; - /** If this is a discriminator model, `baseModelName` is the name of the base model. */ - baseModelName: string; + /** Connection the model uses. */ + db: Connection; + + /** Registered discriminators for this model. */ + discriminators: any; + + /** The name of the model. */ + modelName: string; + + /** Schema the model uses. */ + schema: Schema; /** * Finds a single document by its _id field. findById(id) is almost* @@ -2304,7 +2316,7 @@ declare module "mongoose" { where(path: string, val?: Object): Query; } - interface Document extends MongooseDocument, NodeJS.EventEmitter { + interface Document extends MongooseDocument, NodeJS.EventEmitter, ModelProperties { /** Signal that we desire an increment of this documents version. */ increment(): this; @@ -2328,22 +2340,30 @@ declare module "mongoose" { * @param fn optional callback */ save(fn?: (err: any, product: this, numAffected: number) => void): _MongoosePromise; + } + interface ModelProperties { /** Base Mongoose instance the model uses. */ base: typeof mongoose; + /** * If this is a discriminator model, baseModelName is the * name of the base model. */ baseModelName: String; + /** Collection the model uses. */ collection: Collection; + /** Connection the model uses. */ db: Connection; + /** Registered discriminators for this model. */ discriminators: any; + /** The name of the model */ modelName: string; + /** Schema the model uses. */ schema: Schema; } From 486e24d0a65e774ca301fe6119c34f53a73bbd5e Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 14 Aug 2016 23:55:56 -0400 Subject: [PATCH 091/844] removed extra Model properties --- mongoose/mongoose.d.ts | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index a6a2fc409c..a94644393e 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2059,27 +2059,6 @@ declare module "mongoose" { */ new(doc?: Object): T; - /** Base Mongoose instance the model uses. */ - base: typeof mongoose; - - /** If this is a discriminator model, `baseModelName` is the name of the base model. */ - baseModelName: string; - - /** Collection the model uses. */ - collection: Collection; - - /** Connection the model uses. */ - db: Connection; - - /** Registered discriminators for this model. */ - discriminators: any; - - /** The name of the model. */ - modelName: string; - - /** Schema the model uses. */ - schema: Schema; - /** * Finds a single document by its _id field. findById(id) is almost* * equivalent to findOne({ _id: id }). findById() triggers findOne hooks. From 2854c554b2ffb6b4f42229fd1aa868d72e716885 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 21 Aug 2016 15:44:28 -0400 Subject: [PATCH 092/844] cleanup and update to 4.5.9, changed default promises to global promises to work with typescript 2.x --- mongoose/mongoose-tests.ts | 15 ++-- mongoose/mongoose.d.ts | 150 +++++++++++++++++++------------------ 2 files changed, 84 insertions(+), 81 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index ddec97e9d1..d846023143 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -27,7 +27,7 @@ mongoose.connect(connectUri, { autoIndex: true }, mongos: true -}).then(cb).fulfill(); +}).then(cb); mongoose.connect(connectUri, function (error) { error.stack; }); @@ -45,7 +45,7 @@ mongoose.createConnection('localhost', 'database', 3000, { autoIndex: false } }).open(''); -mongoose.disconnect(cb).then(cb).fulfill; +mongoose.disconnect(cb).then(cb); mongoose.get('test'); mongoose.model('Actor', new mongoose.Schema({ name: String @@ -540,7 +540,7 @@ query.where('loc').within().box(lowerLeft, upperRight) query.box({ ll : lowerLeft, ur : upperRight }).box({}); var queryModel = mongoose.model('QModel') query.cast(new queryModel(), {}).hasOwnProperty(''); -query.catch(function (err) {}).catch(); +query.catch(cb).catch(cb); query.center({}).center({}); query.centerSphere({ center: [50, 50], radius: 10 }).centerSphere('path', {}); query.circle({ center: [50, 50], radius: 10 }).circle('path'); @@ -695,7 +695,7 @@ query.stream().on('data', function (doc: any) { }); query.tailable().tailable(false); query.then(cb).catch(cb); -(new (query.toConstructor())()).toConstructor(); +(new (query.toConstructor())(1, 2, 3)).toConstructor(); query.update({}, doc, { }, cb); @@ -1060,12 +1060,13 @@ mongoose.model('').aggregate() }); /* pluggable promise */ -mongoose.Promise = Promise; +(mongoose).Promise = Promise; +require('mongoose').Promise = Promise; mongoose.Promise.race; mongoose.Promise.all; mongoose.model('').findOne() - .exec().addErrback(cb); + .exec().then(cb); /* * section model.js @@ -1377,5 +1378,5 @@ export var Final: MyModel = mongoose.connection.model('Fina Final.findOne(function (err: any, doc: MyDocument) { doc.save(); doc.remove(); - doc.model(null, null); + doc.model(''); }); \ No newline at end of file diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index a94644393e..b28a222778 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mongoose 4.5.4 +// Type definitions for Mongoose 4.5.9 // Project: http://mongoosejs.com/ // Definitions by: simonxca , horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,7 +6,6 @@ /// /// /// -/// /* * Guidelines for maintaining these definitions: @@ -93,7 +92,6 @@ declare module "mongoose" { * http://mongoosejs.com/docs/api.html#index-js */ export var DocumentProvider: any; - export var Model: Model; // recursive constructor export var Mongoose: new(...args: any[]) => typeof mongoose; export var SchemaTypes: typeof Schema.Types; @@ -107,7 +105,6 @@ declare module "mongoose" { /** The Mongoose version */ export var version: string; - /* Methods */ /** * Opens the default mongoose connection. * Options passed take precedence over options included in connection strings. @@ -173,20 +170,19 @@ declare module "mongoose" { /** Sets mongoose options */ export function set(key: string, value: any): void; - type MongooseThenable = typeof mongoose & _MongooseThenable; - interface _MongooseThenable { + type MongooseThenable = typeof mongoose & { /** * Ability to use mongoose object as a pseudo-promise so .connect().then() * and .disconnect().then() are viable. */ then(onFulfill?: () => void | TRes | PromiseLike, - onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; + onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): Promise; /** * Ability to use mongoose object as a pseudo-promise so .connect().then() * and .disconnect().then() are viable. */ - catch(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; + catch(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): Promise; } class CastError extends Error { @@ -205,7 +201,7 @@ declare module "mongoose" { * http://mongoosejs.com/docs/api.html#querystream-js * * QueryStream can only be accessed using query#stream(), we only - * expose its interface here to enable type-checking. + * expose its interface here. */ interface QueryStream extends stream.Stream { /** @@ -293,7 +289,7 @@ declare module "mongoose" { callback?: (err: any) => void): any; /** Closes the connection */ - close(callback?: (err: any) => void): _MongoosePromise; + close(callback?: (err: any) => void): Promise; /** * Retrieves a collection, creating it if not cached. @@ -375,6 +371,10 @@ declare module "mongoose" { mongos?: boolean; } + interface ConnectOptions extends + ConnectionOpenOptions, + ConnectionOpenSetOptions {} + /* * section drivers/node-mongodb-native/collection.js * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js @@ -412,8 +412,6 @@ declare module "mongoose" { static STATES: Object; } - interface ConnectOptions extends ConnectionOpenOptions, ConnectionOpenSetOptions {} - /* * section error/validation.js * http://mongoosejs.com/docs/api.html#error-validation-js @@ -474,7 +472,7 @@ declare module "mongoose" { constructor(query: Query, options: Object): QueryCursor; /** Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error. */ - close(callback?: (error: any, result: any) => void): _MongoosePromise; + close(callback?: (error: any, result: any) => void): Promise; /** * Execute fn for every document in the cursor. If fn returns a promise, @@ -482,13 +480,13 @@ declare module "mongoose" { * Returns a promise that resolves when done. * @param callback executed when all docs have been processed */ - eachAsync(fn: (doc: T) => any, callback?: (err: any) => void): _MongoosePromise; + eachAsync(fn: (doc: T) => any, callback?: (err: any) => void): Promise; /** * Get the next document from this cursor. Will return null when there are * no documents left. */ - next(callback?: (err: any) => void): _MongoosePromise; + next(callback?: (err: any) => void): Promise; } /* @@ -729,7 +727,7 @@ declare module "mongoose" { * Useful for ES2015 integration. * @returns promise that resolves to the document when population is done */ - execPopulate(): _MongoosePromise; + execPopulate(): Promise; /** * Returns the value of a path. @@ -848,8 +846,8 @@ declare module "mongoose" { * @param optional options internal options * @param callback callback called after validation completes, passing an error if one occurred */ - validate(callback?: (err: any) => void): _MongoosePromise; - validate(optional: Object, callback?: (err: any) => void): _MongoosePromise; + validate(callback?: (err: any) => void): Promise; + validate(optional: Object, callback?: (err: any) => void): Promise; /** * Executes registered validation rules (skipping asynchronous validators) for this document. @@ -915,9 +913,9 @@ declare module "mongoose" { } /* - * section types/array.js - * http://mongoosejs.com/docs/api.html#types-array-js - */ + * section types/array.js + * http://mongoosejs.com/docs/api.html#types-array-js + */ class Array extends global.Array { /** * Atomically shifts the array at most one time per document save(). @@ -1053,9 +1051,9 @@ declare module "mongoose" { } /* - * section types/buffer.js - * http://mongoosejs.com/docs/api.html#types-buffer-js - */ + * section types/buffer.js + * http://mongoosejs.com/docs/api.html#types-buffer-js + */ class Buffer extends global.Buffer { /** * Copies the buffer. @@ -1082,8 +1080,7 @@ declare module "mongoose" { * section types/objectid.js * http://mongoosejs.com/docs/api.html#types-objectid-js */ - var ObjectId: typeof mongodb.ObjectID; - interface ObjectId extends mongodb.ObjectID {} + class ObjectId extends mongodb.ObjectID {} /* * section types/embedded.js @@ -1123,13 +1120,13 @@ declare module "mongoose" { /* * section query.js * http://mongoosejs.com/docs/api.html#query-js + * + * Query is for backwards compatibility. Example: Query.find() returns Query. + * If later in the query chain a method returns Query, we will need to know type T. + * So we save this type as the second type parameter in DocumentQuery. Since people have + * been using Query, we set it as an alias of DocumentQuery. */ class Query extends DocumentQuery {} - - /* - * Query.find() will return Query[]> however we need the - * type T to create this so we save T in another parameter. - */ class DocumentQuery extends mquery { /** * Specifies a javascript function or expression to pass to MongoDBs query system. @@ -1170,7 +1167,7 @@ declare module "mongoose" { * resolved with either the doc(s) or rejected with the error. * Like .then(), but only takes a rejection handler. */ - catch(reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise; + catch(reject?: (err: any) => void | TRes | PromiseLike): Promise; /** * DEPRECATED Alias for circle @@ -1223,8 +1220,8 @@ declare module "mongoose" { equals(val: Object): this; /** Executes the query */ - exec(callback?: (err: any, res: T) => void): _MongoosePromise; - exec(operation: string | Function, callback?: (err: any, res: T) => void): _MongoosePromise; + exec(callback?: (err: any, res: T) => void): Promise; + exec(operation: string | Function, callback?: (err: any, res: T) => void): Promise; /** Specifies an $exists condition */ exists(val?: boolean): this; @@ -1515,13 +1512,14 @@ declare module "mongoose" { /** Executes this query and returns a promise */ then(resolve?: (res: T) => void | TRes | PromiseLike, - reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise; + reject?: (err: any) => void | TRes | PromiseLike): Promise; /** * Converts this query to a customized, reusable query * constructor with all arguments and options retained. */ - toConstructor(): typeof DocumentQuery; + toConstructor(): new(...args: any[]) => Query; + toConstructor(): new(...args: any[]) => DocumentQuery; /** * Declare and/or execute this query as an update() operation. @@ -1858,10 +1856,10 @@ declare module "mongoose" { // If cursor option is on, could return an object /** Executes the aggregate pipeline on the currently bound Model. */ - exec(callback?: (err: any, result: T) => void): _MongoosePromise | any; + exec(callback?: (err: any, result: T) => void): Promise | any; /** Execute the aggregation with explain */ - explain(callback?: (err: any, result: T) => void): _MongoosePromise; + explain(callback?: (err: any, result: T) => void): Promise; /** * Appends a new custom $group operator to this aggregate pipeline. @@ -1936,7 +1934,7 @@ declare module "mongoose" { /** Provides promise for aggregate. */ then(resolve?: (val: T) => void | TRes | PromiseLike, - reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise + reject?: (err: any) => void | TRes | PromiseLike): Promise /** * Appends new custom $unwind operator(s) to this aggregate pipeline. @@ -2004,34 +2002,37 @@ declare module "mongoose" { type?: string): this; } - /** + /* * section promise.js * http://mongoosejs.com/docs/api.html#promise-js - * - * You must assign a promise library: - * - * 1. To use mongoose's default promise library: - * Install mongoose-promise.d.ts - * - * 2. To use native ES6 promises, add this line to your main .d.ts file: - * type MongoosePromise = Promise; - * - * 3. To use another promise library (for example q): - * Install q.d.ts - * Then add this line to your main .d.ts file: - * type MongoosePromise = Q.Promise; */ - interface _MongoosePromise extends MongoosePromise {} - interface Promise extends MongoosePromise {} - /** * To assign your own promise library: * - * 1. Include this somewhere in your code: - * mongoose.Promise = YOUR_PROMISE; + * 1. Typescript does not allow assigning properties of imported modules. + * To avoid compile errors use one of the options below in your code: * - * 2. Include this somewhere in your main .d.ts file: - * type MongoosePromise = YOUR_PROMISE; + * - (mongoose).Promise = YOUR_PROMISE; + * - require('mongoose').Promise = YOUR_PROMISE; + * - import mongoose = require('mongoose'); + * mongoose.Promise = YOUR_PROMISE; + * + * 2. To assign type definitions for your promise library, you will need + * to have a .d.ts file with the following code when you compile: + * + * - import * as Q from 'q'; + * declare module 'mongoose' { + * type Promise = Q.promise; + * } + * + * - import * as Bluebird from 'bluebird'; + * declare module 'mongoose' { + * type Promise = Bluebird; + * } + * + * Uses global.Promise by default. If you would like to use mongoose default + * mpromise implementation (which is deprecated), you can omit step 1 and + * run npm install @types/mongoose-promise */ export var Promise: any; export var PromiseProvider: any; @@ -2040,6 +2041,7 @@ declare module "mongoose" { * section model.js * http://mongoosejs.com/docs/api.html#model-js */ + export var Model: Model; interface Model extends NodeJS.EventEmitter, ModelProperties { /** * Model constructor @@ -2087,7 +2089,7 @@ declare module "mongoose" { * @param ... aggregation pipeline operator(s) or operator array */ aggregate(...aggregations: Object[]): Aggregate; - aggregate(...aggregationsWithCallback: Object[]): _MongoosePromise; + aggregate(...aggregationsWithCallback: Object[]): Promise; /** Counts number of matching documents in a database collection. */ count(conditions: Object, callback?: (err: any, count: number) => void): Query; @@ -2097,9 +2099,9 @@ declare module "mongoose" { * does new MyModel(doc).save() for every doc in docs. * Triggers the save() hook. */ - create(docs: any[], callback?: (err: any, res: T[]) => void): _MongoosePromise; - create(...docs: Object[]): _MongoosePromise; - create(...docsWithCallback: Object[]): _MongoosePromise; + create(docs: any[], callback?: (err: any, res: T[]) => void): Promise; + create(...docs: Object[]): Promise; + create(...docsWithCallback: Object[]): Promise; /** * Adds a discriminator type. @@ -2118,8 +2120,8 @@ declare module "mongoose" { * @param options internal options * @param cb optional callback */ - ensureIndexes(callback?: (err: any) => void): _MongoosePromise; - ensureIndexes(options: Object, callback?: (err: any) => void): _MongoosePromise; + ensureIndexes(callback?: (err: any) => void): Promise; + ensureIndexes(options: Object, callback?: (err: any) => void): Promise; /** * Finds documents. @@ -2254,9 +2256,9 @@ declare module "mongoose" { * document. * This function does not trigger save middleware. */ - insertMany(docs: any[], callback?: (error: any, docs: T[]) => void): _MongoosePromise; - insertMany(doc: any, callback?: (error: any, doc: T) => void): _MongoosePromise; - insertMany(...docsWithCallback: Object[]): _MongoosePromise; + insertMany(docs: any[], callback?: (error: any, docs: T[]) => void): Promise; + insertMany(doc: any, callback?: (error: any, doc: T) => void): Promise; + insertMany(...docsWithCallback: Object[]): Promise; /** * Executes a mapReduce command. @@ -2266,7 +2268,7 @@ declare module "mongoose" { mapReduce( o: ModelMapReduceOption, callback?: (err: any, res: any) => void - ): _MongoosePromise; + ): Promise; /** * Populates document references. @@ -2275,9 +2277,9 @@ declare module "mongoose" { * @param callback Optional callback, executed upon completion. Receives err and the doc(s). */ populate(docs: Object[], options: ModelPopulateOptions | ModelPopulateOptions[], - callback?: (err: any, res: T[]) => void): _MongoosePromise; + callback?: (err: any, res: T[]) => void): Promise; populate(docs: Object, options: ModelPopulateOptions | ModelPopulateOptions[], - callback?: (err: any, res: T) => void): _MongoosePromise; + callback?: (err: any, res: T) => void): Promise; /** Removes documents from the collection. */ remove(conditions: Object, callback?: (err: any) => void): Query; @@ -2309,7 +2311,7 @@ declare module "mongoose" { * Removes this document from the db. * @param fn optional callback */ - remove(fn?: (err: any, product: this) => void): _MongoosePromise; + remove(fn?: (err: any, product: this) => void): Promise; /** * Saves this document. @@ -2318,7 +2320,7 @@ declare module "mongoose" { * @param options.validateBeforeSave set to false to save without validating. * @param fn optional callback */ - save(fn?: (err: any, product: this, numAffected: number) => void): _MongoosePromise; + save(fn?: (err: any, product: this, numAffected: number) => void): Promise; } interface ModelProperties { From 3f9a9295bf92950347ffcb7b311a9e8a0d03633c Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 21 Aug 2016 15:49:27 -0400 Subject: [PATCH 093/844] updates mongoose-paginate to work with new mongoose interfaces --- mongoose-paginate/mongoose-paginate-tests.ts | 8 ++++---- mongoose-paginate/mongoose-paginate.d.ts | 7 +++---- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/mongoose-paginate/mongoose-paginate-tests.ts b/mongoose-paginate/mongoose-paginate-tests.ts index 7857ffda33..42fc42be69 100644 --- a/mongoose-paginate/mongoose-paginate-tests.ts +++ b/mongoose-paginate/mongoose-paginate-tests.ts @@ -11,14 +11,15 @@ import { model, PaginateModel, PaginateOptions, - PaginateResult + PaginateResult, + Document } from 'mongoose'; import * as mongoosePaginate from 'mongoose-paginate'; import { Router, Request, Response } from 'express'; //#region Test Models -interface User { +interface User extends Document { email: string; username: string; password: string; @@ -32,8 +33,7 @@ const UserSchema: Schema = new Schema({ UserSchema.plugin(mongoosePaginate); -type UserModel = _UserModel & PaginateModel; -interface _UserModel {} +interface UserModel extends PaginateModel {}; let UserModel: UserModel = model('User', UserSchema) as UserModel; //#endregion diff --git a/mongoose-paginate/mongoose-paginate.d.ts b/mongoose-paginate/mongoose-paginate.d.ts index 5481c42775..c90e7550fd 100644 --- a/mongoose-paginate/mongoose-paginate.d.ts +++ b/mongoose-paginate/mongoose-paginate.d.ts @@ -26,16 +26,15 @@ declare module 'mongoose' { offset?: number; } - export type PaginateModel = _PaginateModel & Model; - interface _PaginateModel { + interface PaginateModel extends Model { paginate(query?: Object, options?: PaginateOptions, callback?: (err: any, result: PaginateResult) => void): Promise>; } - export function model( + export function model( name: string, schema?: Schema, collection?: string, - skipInit?: boolean): Statics & PaginateModel; + skipInit?: boolean): PaginateModel; } declare module 'mongoose-paginate' { From f00d294bf6f8827e7396e58dfc381815729e8e00 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 21 Aug 2016 15:54:13 -0400 Subject: [PATCH 094/844] updates passport-local-mongoose to use mongoose intefaces instead of type intersections --- passport-local-mongoose/passport-local-mongoose-tests.ts | 7 +++---- passport-local-mongoose/passport-local-mongoose.d.ts | 9 ++++----- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/passport-local-mongoose/passport-local-mongoose-tests.ts b/passport-local-mongoose/passport-local-mongoose-tests.ts index cf41176f08..993d5b05da 100644 --- a/passport-local-mongoose/passport-local-mongoose-tests.ts +++ b/passport-local-mongoose/passport-local-mongoose-tests.ts @@ -77,10 +77,9 @@ options.errorMessages = errorMessages; UserSchema.plugin(passportLocalMongoose, options); -type UserModel = _UserModel & PassportLocalModel; -interface _UserModel {} +interface UserModel extends PassportLocalModel {} -let UserModel: UserModel = model('User', UserSchema) as UserModel; +let UserModel: UserModel = model('User', UserSchema); //#endregion @@ -96,7 +95,7 @@ passport.use('login', new LocalStrategy({ process.nextTick(() => { UserModel .findOne({ 'username': username }) - .exec((err: any, user: model) => { + .exec((err: any, user: User) => { if (err) { console.log(err); return done(err, null); diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts index 8e4a6bb777..acb834d85c 100644 --- a/passport-local-mongoose/passport-local-mongoose.d.ts +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -10,14 +10,13 @@ declare module 'mongoose' { import passportLocal = require('passport-local'); // methods - export interface PassportLocalDocument { + export interface PassportLocalDocument extends Document { setPassword(password: string, cb: (err: any, res: any) => void): void; authenticate(password: string, cb: (err: any, res: any, error: any) => void): void; } // statics - export type PassportLocalModel = _PassportLocalModel & Model; - interface _PassportLocalModel { + interface PassportLocalModel extends Model { authenticate(): (username: string, password: string, cb: (err: any, res: T, error: any) => void) => void; serializeUser(): (user: PassportLocalModel, cb: (err: any) => void) => void; deserializeUser(): (username: string, cb: (err: any) => void) => void; @@ -77,11 +76,11 @@ declare module 'mongoose' { ): this; } - export function model( + export function model( name: string, schema?: PassportLocalSchema, collection?: string, - skipInit?: boolean): Statics & PassportLocalModel; + skipInit?: boolean): PassportLocalModel; } declare module 'passport-local-mongoose' { From 85290f2ffb682ab4aab67fc77253183079ec426d Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 21 Aug 2016 15:54:53 -0400 Subject: [PATCH 095/844] adds a README for mongoose --- mongoose/README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 mongoose/README.md diff --git a/mongoose/README.md b/mongoose/README.md new file mode 100644 index 0000000000..4a581dcfdb --- /dev/null +++ b/mongoose/README.md @@ -0,0 +1 @@ +# TESTING \ No newline at end of file From 5ed0b6507603f37bab7bfef280c6d7ffa372c711 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 21 Aug 2016 22:24:13 -0400 Subject: [PATCH 096/844] adds a README plus better tests --- mongoose/README.md | 192 +++++++++++++++++- mongoose/mongoose-tests.ts | 8 +- mongoose/mongoose.d.ts | 15 +- .../passport-local-mongoose-tests.ts | 2 +- 4 files changed, 212 insertions(+), 5 deletions(-) diff --git a/mongoose/README.md b/mongoose/README.md index 4a581dcfdb..03b483ecd1 100644 --- a/mongoose/README.md +++ b/mongoose/README.md @@ -1 +1,191 @@ -# TESTING \ No newline at end of file +## MongooseJS Typescript Docs +Below are some examples of how to use these Definitions.
    +Scenarios where the Typescript code is identical to plain Javascript code are omitted. + +#### Mongoose Methods, Properties, Constructors +You can call methods from the mongoose instance using: +``` +import * as mongoose from 'mongoose'; +var MyModel = mongoose.model(...); +var MySchema: mongoose.Schema = new mongoose.Schema(...); +``` + +Alternatively, you can import individual names and call them: +``` +import {model, Schema} from 'mongoose'; +var MyModel = model(...); +var MySchema: Schema = new Schema(...): +``` + + +#### Creating and Saving Documents +``` +import {Document, model, Model, Schema} from 'mongoose'; + +var UserSchema: Schema = new Schema({ + username: { + type: String, + required: true, + unique: true + }, + age: Number, + friends: [String], + data: [Schema.Types.Mixed] +}); + +interface IUser extends Document { + username: string; + age: number; + friends: string[]; + data: any[]; +} + +var UserModel: Model = mongoose.model('User', UserSchema); + +var user = new UserModel({name: 'Jane'}); +user.username; // IUser properties are available +user.save(); // mongoose Document methods are available + +UserModel.findOne({}, (err: any, user: IUser) => { + user.username; // IUser properties are available + user.save(); // mongoose Document methods are available +}); +``` + +#### Instance Methods and Virtual Properties +``` +import {Document, model, Model, Schema} from 'mongoose'; + +var UserSchema: Schema = new Schema({ + name: String +}); + +UserSchema.methods.method1 = function () { return '' }; +UserSchema.virtual('nameInCaps').get(function () { + return this.name.toUpperCase(); +}); +UserSchema.virtual('nameInCaps').set(function (caps) { + this.name = caps.toLowerCase(); +}); + +interface IUser extends Document { + name: string; + nameInCaps: string; + method1: () => string; +} + +var UserModel: Model = model('User', UserSchema); +var user = new UserModel({name: 'Billy'}); + +user.method1(); // IUser methods are available +user.nameInCaps; // virtual properties can be used + +UserModel.findOne({}, (err: any, user: IUser) => { + user.method1(); // IUser methods are available + user.nameInCaps; // virtual properties can be used +}); +``` + +#### Static Methods +``` +import {Document, model, Model, Schema} from 'mongoose'; + +var UserSchema = new Schema({}); +UserSchema.statics.static1 = function () { return '' }; + +interface IUserDocument extends Document {...} +interface IUserModel extends Model { + static1: () => string; +} + +var UserModel: IUserModel = model('User', UserSchema); +UserModel.static1(); // static methods are available +``` + +#### Plugins +To write definitions for plugins, extend the mongoose module and create a simple plugin module: +``` +// plugin.d.ts +declare module 'mongoose' { + export interface PassportLocalDocument {...} + export interface PassportLocalSchema extends Schema {...} + export interface PassportLocalModel extends Model {...} + ... +} + +declare module 'passport-local-mongoose' { + import mongoose = require('mongoose'); + var _: (schema: mongoose.Schema, options?: Object) => void; + export = _; +} + +// user.ts +import { + model, + PassportLocalDocument, + PassportLocalSchema, + PassportLocalModel + Schema +} from 'mongoose'; +import * as passportLocalMongoose from 'passport-local-mongoose'; + +var UserSchema: PassportLocalSchema = new Schema({}); +UserSchema.plugin(passportLocalMongoose, options); + +interface IUser extends PassportLocalDocument {...} +interface IUserModel extends PassportLocalModel {...} + +var UserModel: IUserModel = model('User', UserSchema); +``` +Full example for [Passport Local Mongoose](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/passport-local-mongoose/passport-local-mongoose.d.ts) + +#### Promises +These definitions use global.Promise by default. If you would like to use mongoose's own mpromise +definition (which is deprecated), you can install definitions for [mongoose-promise](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/mongoose-promise). + +If you'd like to use something other than global.Promise, you'll need to create a simple .d.ts file: +``` +// promise-bluebird.d.ts +import * as Bluebird from 'bluebird'; + +declare module 'mongoose' { + type Promise = Bluebird; +} + +// promise-q.d.ts +import * as Q from 'q'; + +declare module 'mongoose' { + type Promise = Q.Promise; +} + +// another-promise.d.ts +... +``` +To use it, you will need to `/// ` in one of your source code files, +or include the `.d.ts` file in your compile. + +To assign the new promise library in your code, you will need to use one of the following options (since +Typescript does not allow assigning properties of imported modules): + +* `(mongoose).Promise = YOUR_PROMISE;` +* `require('mongoose').Promise = YOUR_PROMISE;` +* `import mongoose = require('mongoose'); ... mongoose.Promise = YOUR_PROMISE;` + +#### FAQ +Q: Why are there 2 interfaces for Documents called Document and MongooseDocument?
    +A: People have been using this for a long time: +``` +interface IUser extends mongoose.Document { + ... +} +``` +When it should really be this: +``` +interface IUser extends mongoose.model { + ... +} +``` +For backwards compatibility Document is an interface for [mongoose.model](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)
    +And MongooseDocument is an interface for [mongoose.Document](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)
    +At some point in the future this may get fixed, which would require fixing your code. \ No newline at end of file diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index d846023143..51959b9e41 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1379,4 +1379,10 @@ Final.findOne(function (err: any, doc: MyDocument) { doc.save(); doc.remove(); doc.model(''); -}); \ No newline at end of file +}); +export var Final2: MyModel = mongoose.model('Final2', mySchema); +Final2.staticMethod(); +Final2.staticProp; +var final2 = new Final2(); +final2.prop; +final2.method; \ No newline at end of file diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index b28a222778..81247104ef 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -152,6 +152,12 @@ declare module "mongoose" { */ export function model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; + export function model>( + name: string, + schema?: Schema, + collection?: string, + skipInit?: boolean + ): U; /** * Returns an array of model names created on this instance of Mongoose. @@ -311,6 +317,11 @@ declare module "mongoose" { * @returns The compiled model */ model(name: string, schema?: Schema, collection?: string): Model; + model>( + name: string, + schema?: Schema, + collection?: string + ): U; /** Returns an array of model names created on this connection. */ modelNames(): string[]; @@ -704,7 +715,7 @@ declare module "mongoose" { * section document.js * http://mongoosejs.com/docs/api.html#document-js */ - class MongooseDocument { + interface MongooseDocument { /** Checks if a path is set to its default. */ $isDefault(path?: string): boolean; @@ -2074,7 +2085,7 @@ declare module "mongoose" { findById(id: Object | string | number, projection: Object, options: Object, callback?: (err: any, res: T) => void): DocumentQuery; - model(name: string): Model; + model(name: string): Model; /** * Creates a Query and specifies a $where condition. diff --git a/passport-local-mongoose/passport-local-mongoose-tests.ts b/passport-local-mongoose/passport-local-mongoose-tests.ts index 993d5b05da..c7d4ffc381 100644 --- a/passport-local-mongoose/passport-local-mongoose-tests.ts +++ b/passport-local-mongoose/passport-local-mongoose-tests.ts @@ -34,7 +34,7 @@ interface User extends PassportLocalDocument { last: Date; } -const UserSchema: PassportLocalSchema = new Schema({ +const UserSchema: PassportLocalSchema = new Schema({ username: String, hash: String, salt: String, From 697685356ed872a4c754d86ac33cf9b56f967409 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 21 Aug 2016 22:36:44 -0400 Subject: [PATCH 097/844] adds table of contents to readme --- mongoose/README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/mongoose/README.md b/mongoose/README.md index 03b483ecd1..fa3b695c91 100644 --- a/mongoose/README.md +++ b/mongoose/README.md @@ -2,6 +2,15 @@ Below are some examples of how to use these Definitions.
    Scenarios where the Typescript code is identical to plain Javascript code are omitted. +### Table of Contents +* [Mongoose Methods, Properties, Constructors](#mongoose-methods-properties-constructors) +* [Creating and Saving Documents](#creating-and-saving-documents) +* [Instance Methods, Virtual Properties](#instance-methods-and-virtual-properties) +* [Static Methods](#static-methods) +* [Plugins](#plugins) +* [Promises](#promises) +* [FAQ](#faq) + #### Mongoose Methods, Properties, Constructors You can call methods from the mongoose instance using: ``` From aa1c6efe5106663df8dea5c13652af23fd1a9f28 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 21 Aug 2016 22:40:03 -0400 Subject: [PATCH 098/844] adds links in each section to top of README --- mongoose/README.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/mongoose/README.md b/mongoose/README.md index fa3b695c91..1d8c7083f9 100644 --- a/mongoose/README.md +++ b/mongoose/README.md @@ -25,7 +25,7 @@ import {model, Schema} from 'mongoose'; var MyModel = model(...); var MySchema: Schema = new Schema(...): ``` - +[top](#mongoosejs-typescript-docs) #### Creating and Saving Documents ``` @@ -60,6 +60,7 @@ UserModel.findOne({}, (err: any, user: IUser) => { user.save(); // mongoose Document methods are available }); ``` +[top](#mongoosejs-typescript-docs) #### Instance Methods and Virtual Properties ``` @@ -94,6 +95,7 @@ UserModel.findOne({}, (err: any, user: IUser) => { user.nameInCaps; // virtual properties can be used }); ``` +[top](#mongoosejs-typescript-docs) #### Static Methods ``` @@ -110,6 +112,7 @@ interface IUserModel extends Model { var UserModel: IUserModel = model('User', UserSchema); UserModel.static1(); // static methods are available ``` +[top](#mongoosejs-typescript-docs) #### Plugins To write definitions for plugins, extend the mongoose module and create a simple plugin module: @@ -147,6 +150,7 @@ interface IUserModel extends PassportLocalModel var UserModel: IUserModel = model('User', UserSchema); ``` Full example for [Passport Local Mongoose](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/passport-local-mongoose/passport-local-mongoose.d.ts) +[top](#mongoosejs-typescript-docs) #### Promises These definitions use global.Promise by default. If you would like to use mongoose's own mpromise @@ -180,6 +184,7 @@ Typescript does not allow assigning properties of imported modules): * `(mongoose).Promise = YOUR_PROMISE;` * `require('mongoose').Promise = YOUR_PROMISE;` * `import mongoose = require('mongoose'); ... mongoose.Promise = YOUR_PROMISE;` +[top](#mongoosejs-typescript-docs) #### FAQ Q: Why are there 2 interfaces for Documents called Document and MongooseDocument?
    @@ -197,4 +202,5 @@ interface IUser extends mongoose.model { ``` For backwards compatibility Document is an interface for [mongoose.model](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)
    And MongooseDocument is an interface for [mongoose.Document](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)
    -At some point in the future this may get fixed, which would require fixing your code. \ No newline at end of file +At some point in the future this may get fixed, which would require fixing your code. +[top](#mongoosejs-typescript-docs) \ No newline at end of file From d2a6d1b94c791829b41605efbc98ba50a7569f1b Mon Sep 17 00:00:00 2001 From: Simon Xiong Date: Sun, 21 Aug 2016 22:42:19 -0400 Subject: [PATCH 099/844] Fix README formatting --- mongoose/README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/mongoose/README.md b/mongoose/README.md index 1d8c7083f9..411f6ace2e 100644 --- a/mongoose/README.md +++ b/mongoose/README.md @@ -149,7 +149,7 @@ interface IUserModel extends PassportLocalModel var UserModel: IUserModel = model('User', UserSchema); ``` -Full example for [Passport Local Mongoose](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/passport-local-mongoose/passport-local-mongoose.d.ts) +Full example for [Passport Local Mongoose](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/passport-local-mongoose/passport-local-mongoose.d.ts)
    [top](#mongoosejs-typescript-docs) #### Promises @@ -184,6 +184,7 @@ Typescript does not allow assigning properties of imported modules): * `(mongoose).Promise = YOUR_PROMISE;` * `require('mongoose').Promise = YOUR_PROMISE;` * `import mongoose = require('mongoose'); ... mongoose.Promise = YOUR_PROMISE;` + [top](#mongoosejs-typescript-docs) #### FAQ @@ -203,4 +204,5 @@ interface IUser extends mongoose.model { For backwards compatibility Document is an interface for [mongoose.model](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)
    And MongooseDocument is an interface for [mongoose.Document](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)
    At some point in the future this may get fixed, which would require fixing your code. -[top](#mongoosejs-typescript-docs) \ No newline at end of file +
    +[top](#mongoosejs-typescript-docs) From aff3e68242a9a63e2ff7592a82159c5ef4eadafc Mon Sep 17 00:00:00 2001 From: Simon Date: Mon, 22 Aug 2016 12:19:41 -0400 Subject: [PATCH 100/844] changes mongoose mpromise to be compatible with new mongoose promise implemenation fixes #10743 --- mongoose-promise/mongoose-promise-tests.ts | 20 +- mongoose-promise/mongoose-promise.d.ts | 231 ++++++++++----------- mongoose/mongoose.d.ts | 3 +- 3 files changed, 133 insertions(+), 121 deletions(-) diff --git a/mongoose-promise/mongoose-promise-tests.ts b/mongoose-promise/mongoose-promise-tests.ts index e7bda80c6d..a7908c3db5 100644 --- a/mongoose-promise/mongoose-promise-tests.ts +++ b/mongoose-promise/mongoose-promise-tests.ts @@ -1,8 +1,10 @@ /// +import * as mongoose from 'mongoose'; + var cb = function () {}; -var mongopromise: MongoosePromise; +var mongopromise: mongoose.Promise; mongopromise.addBack(function (err, arg) { err.stack; arg.toFixed(); @@ -40,7 +42,19 @@ mongopromise.then(function (arg) { }); mongopromise.complete(); /* static properties */ -MongoosePromise.ES6(function (complete, error) { +mongoose.Promise.ES6(function (complete, error) { complete.apply(this); error.apply(this); -}); \ No newline at end of file +}); +/* Practical Examples */ +interface IUser extends mongoose.Document { + name: string; + age: number; +} +var UserSchema = new mongoose.Schema({ + name: String, + age: Number +}); +var UserModel: mongoose.Model = mongoose.model('Model', UserSchema); +UserModel.findOne({}).exec().fulfill(); +UserModel.find({}).exec().then(() => {}).catch(() => {}).reject(''); \ No newline at end of file diff --git a/mongoose-promise/mongoose-promise.d.ts b/mongoose-promise/mongoose-promise.d.ts index d2622bb6f9..b5699e657e 100644 --- a/mongoose-promise/mongoose-promise.d.ts +++ b/mongoose-promise/mongoose-promise.d.ts @@ -3,126 +3,125 @@ // Definitions by: simonxca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/* - * These are the default promises included in the Mongoose v4.x - * definitions. They will be deprecated beginning Mongoose V5.x - * in favor of native ES6 Promises. - * - * You can switch the promise library that mongoose uses by: - * - * 1. Including this somewhere in your code: - * mongoose.Promise = YOUR_PROMISE; - * - * 2. Including this somewhere in your main .d.ts file: - * type MongoosePromise = YOUR_PROMISE; - */ +/// +/// /* * http://mongoosejs.com/docs/api.html#promise-js * - * Callback signatures are from the mPromise type definitions. + * mongoose.d.ts uses global.Promise by default. This is the MongooseJS + * mpromise implementation (which are deprecated). If you still want to + * use it, install these definitions in your project. */ -interface MongoosePromise { - /** - * Promise constructor. - * Promises are returned from executed queries. - * @param fn a function which will be called when the promise - * is resolved that accepts fn(err, ...){} as signature - * @event err Emits when the promise is rejected - * @event complete Emits when the promise is fulfilled - * @deprecated Mongoose 5.0 will use native promises by default (or bluebird, if native - * promises are not present) but still support plugging in your own ES6-compatible - * promises library. Mongoose 5.0 will not support mpromise. +declare module 'mongoose' { + import mpromise = require('mpromise'); + + type Promise = MongoosePromise; + + /* + * mpromise definitions. + * Callback signatures are from the mPromise type definitions. */ - new(fn?: (err: any, arg: T) => void): MongoosePromise; - new(fn?: (err: any, ...args: T[]) => void): MongoosePromise; + class MongoosePromise extends mpromise { + /** + * Promise constructor. + * Promises are returned from executed queries. + * @param fn a function which will be called when the promise + * is resolved that accepts fn(err, ...){} as signature + * @event err Emits when the promise is rejected + * @event complete Emits when the promise is fulfilled + * @deprecated Mongoose 5.0 will use native promises by default (or bluebird, if native + * promises are not present) but still support plugging in your own ES6-compatible + * promises library. Mongoose 5.0 will not support mpromise. + */ + constructor(fn?: (err: any, arg: T) => void); + constructor(fn?: (err: any, ...args: T[]) => void); + + /** + * Adds a single function as a listener to both err and complete. + * It will be executed with traditional node.js argument position when the promise is resolved. + * @deprecated Use onResolve instead. + */ + addBack(listener: (err: any, arg: T) => void): this; + addBack(listener: (err: any, ...args: T[]) => void): this; + + /** + * Adds a listener to the complete (success) event. + * @deprecated Adds a listener to the complete (success) event. + */ + addCallback(listener: (arg: T) => void): this; + addCallback(listener: (...args: T[]) => void): this; + + /** + * Adds a listener to the err (rejected) event. + * @deprecated Use onReject instead. + */ + addErrback(listener: (err: any) => void): this; + + /** ES6-style .catch() shorthand */ + catch(onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; + + /** + * Signifies that this promise was the last in a chain of then()s: if a handler passed + * to the call to then which produced this promise throws, the exception will go uncaught. + */ + end(): void; + + /** + * Rejects this promise with err. + * If the promise has already been fulfilled or rejected, not action is taken. + * Differs from #reject by first casting err to an Error if it is not instanceof Error. + */ + error(err: any): this; + + /** + * Adds listener to the event. + * If event is either the success or failure event and the event has already been emitted, + * thelistener is called immediately and passed the results of the original emitted event. + */ + on(event: string, listener: Function): this; + + /** + * Rejects this promise with reason. + * If the promise has already been fulfilled or rejected, not action is taken. + */ + reject(reason: Object | string | Error): this; + + /** + * Resolves this promise to a rejected state if err is passed or a fulfilled state if no err is passed. + * If the promise has already been fulfilled or rejected, not action is taken. + * err will be cast to an Error if not already instanceof Error. + * NOTE: overrides mpromise#resolve to provide error casting. + * @param err error or null + * @param val value to fulfill the promise with + */ + resolve(err?: any, val?: Object): this; + + /** + * Creates a new promise and returns it. If onFulfill or onReject are passed, they are added as + * SUCCESS/ERROR callbacks to this promise after the nextTick. + * Conforms to promises/A+ specification. + */ + then(onFulFill: (arg: T) => void | TRes | PromiseLike, + onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; + then(onFulfill: (...args: T[]) => void | TRes | PromiseLike, + onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; + + /** + * Fulfills this promise with passed arguments. Alias of mpromise#fulfill. + * @deprecated Use fulfill instead. + */ + complete(args: T): this; + complete(...args: T[]): this; + + /** Fulfills this promise with passed arguments. */ + fulfill(...args: T[]): this; + fulfill(arg: T): this; + + /** ES6-style promise constructor wrapper around mpromise. */ + static ES6(resolver: ( + complete: (...args: TRes[]) => void | TRes | PromiseLike, + error: (e: any) => void | TRes | PromiseLike + ) => void): MongoosePromise; + } } - -declare class MongoosePromise { - /** - * Adds a single function as a listener to both err and complete. - * It will be executed with traditional node.js argument position when the promise is resolved. - * @deprecated Use onResolve instead. - */ - addBack(listener: (err: any, arg: T) => void): this; - addBack(listener: (err: any, ...args: T[]) => void): this; - - /** - * Adds a listener to the complete (success) event. - * @deprecated Adds a listener to the complete (success) event. - */ - addCallback(listener: (arg: T) => void): this; - addCallback(listener: (...args: T[]) => void): this; - - /** - * Adds a listener to the err (rejected) event. - * @deprecated Use onReject instead. - */ - addErrback(listener: (err: any) => void): this; - - /** ES6-style .catch() shorthand */ - catch(onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; - - /** - * Signifies that this promise was the last in a chain of then()s: if a handler passed - * to the call to then which produced this promise throws, the exception will go uncaught. - */ - end(): void; - - /** - * Rejects this promise with err. - * If the promise has already been fulfilled or rejected, not action is taken. - * Differs from #reject by first casting err to an Error if it is not instanceof Error. - */ - error(err: any): this; - - /** - * Adds listener to the event. - * If event is either the success or failure event and the event has already been emitted, - * thelistener is called immediately and passed the results of the original emitted event. - */ - on(event: string, listener: Function): this; - - /** - * Rejects this promise with reason. - * If the promise has already been fulfilled or rejected, not action is taken. - */ - reject(reason: Object | string | Error): this; - - /** - * Resolves this promise to a rejected state if err is passed or a fulfilled state if no err is passed. - * If the promise has already been fulfilled or rejected, not action is taken. - * err will be cast to an Error if not already instanceof Error. - * NOTE: overrides mpromise#resolve to provide error casting. - * @param err error or null - * @param val value to fulfill the promise with - */ - resolve(err?: any, val?: Object): this; - - /** - * Creates a new promise and returns it. If onFulfill or onReject are passed, they are added as - * SUCCESS/ERROR callbacks to this promise after the nextTick. - * Conforms to promises/A+ specification. - */ - then(onFulFill: (arg: T) => void | TRes | PromiseLike, - onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; - then(onFulfill: (...args: T[]) => void | TRes | PromiseLike, - onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; - - /** - * Fulfills this promise with passed arguments. Alias of mpromise#fulfill. - * @deprecated Use fulfill instead. - */ - complete(args: T): this; - complete(...args: T[]): this; - - /** Fulfills this promise with passed arguments. */ - fulfill(...args: T[]): this; - fulfill(arg: T): this; - - /** ES6-style promise constructor wrapper around mpromise. */ - static ES6(resolver: ( - complete: (...args: TRes[]) => void | TRes | PromiseLike, - error: (e: any) => void | TRes | PromiseLike - ) => void): MongoosePromise; -} \ No newline at end of file diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 81247104ef..50784a9194 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// /// /* @@ -715,7 +714,7 @@ declare module "mongoose" { * section document.js * http://mongoosejs.com/docs/api.html#document-js */ - interface MongooseDocument { + class MongooseDocument { /** Checks if a path is set to its default. */ $isDefault(path?: string): boolean; From 198bb0ca9a8cbe7060bb5c75f883bbdc0c35d014 Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Mon, 22 Aug 2016 22:58:55 +0200 Subject: [PATCH 101/844] Add missing method --- github-electron/github-electron.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 7b246966ab..f2fe5c3ba4 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -4766,6 +4766,10 @@ declare namespace Electron { * @returns Whether the web page is destroyed. */ isDestroyed(): boolean; + /** + * @returns Whether the web page is focused. + */ + isFocused(): boolean; /** * @returns Whether guest page is still loading resources. */ From 47fd4a64545cba40a70b6f52db5f1bf87f73939b Mon Sep 17 00:00:00 2001 From: Brett Beatty Date: Mon, 22 Aug 2016 15:54:32 -0600 Subject: [PATCH 102/844] adding CloudFormation to AWS --- aws-sdk/aws-sdk.d.ts | 239 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 239 insertions(+) diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index cb35f34e97..401babd4e0 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -118,6 +118,37 @@ declare module "aws-sdk" { region: string; } + export class CloudFormation { + constructor(options?: CloudFormation.Options); + endpoint: Endpoint; + + cancelUpdateStack(params: CloudFormation.CancelUpdateStackParams, callback: (err: AwsError, data: any) => void): void; + continueUpdateRollback(params: CloudFormation.ContinueUpdateRollbackParams, callback: (err: AwsError, data: any) => void): void; + createChangeSet(params: CloudFormation.CreateChangeSetParams, callback: (err: AwsError, data: any) => void): void; + createStack(params: CloudFormation.CreateStackParams, callback: (err: AwsError, data: any) => void): void; + deleteChangeSet(params: CloudFormation.DeleteChangeSetParams, callback: (err: AwsError, data: any) => void): void; + deleteStack(params: CloudFormation.DeleteStackParams, callback: (err: AwsError, data: any) => void): void; + describeAccountLimits(params: CloudFormation.DescribeAccountLimitsParams, callback: (err: AwsError, data: any) => void): void; + describeChangeSet(params: CloudFormation.DescribeChangeSetParams, callback: (err: AwsError, data: any) => void): void; + describeStackEvents(params: CloudFormation.DescribeStackEventsParams, callback: (err: AwsError, data: any) => void): void; + describeStackResource(params: CloudFormation.DescribeStackResourceParams, callback: (err: AwsError, data: any) => void): void; + describeStackResources(params: CloudFormation.DescribeStackResourcesParams, callback: (err: AwsError, data: any) => void): void; + describeStacks(params: CloudFormation.DescribeStacksParams, callback: (err: AwsError, data: any) => void): void; + estimateTemplateCost(params: CloudFormation.EstimateTemplateCostParams, callback: (err: AwsError, data: any) => void): void; + executeChangeSet(params: CloudFormation.ExecuteChangeSetParams, callback: (err: AwsError, data: any) => void): void; + getStackPolicy(params: CloudFormation.GetStackPolicyParams, callback: (err: AwsError, data: any) => void): void; + getTemplate(params: CloudFormation.GetTemplateParams, callback: (err: AwsError, data: any) => void): void; + getTemplateSummary(params: CloudFormation.GetTemplateSummaryParams, callback: (err: AwsError, data: any) => void): void; + listChangeSets(params: CloudFormation.ListChangeSetsParams, callback: (err: AwsError, data: any) => void): void; + listStackResources(params: CloudFormation.ListStackResourcesParams, callback: (err: AwsError, data: any) => void): void; + listStacks(params: CloudFormation.ListStacksParams, callback: (err: AwsError, data: any) => void): void; + setStackPolicy(params: CloudFormation.SetStackPolicyParams, callback: (err: AwsError, data: any) => void): void; + signalResource(params: CloudFormation.SignalResourceParams, callback: (err: AwsError, data: any) => void): void; + updateStack(params: CloudFormation.UpdateStackParams, callback: (err: AwsError, data: any) => void): void; + validateTemplate(params: CloudFormation.ValidateTemplateParams, callback: (err: AwsError, data: any) => void): void; + waitFor(state: string, params: CloudFormation.WaitForParams, callback: (err: AwsError, data: any) => void): void; + } + export class Lambda { constructor(options?: any); endpoint: Endpoint; @@ -423,6 +454,214 @@ declare module "aws-sdk" { // =========================================================== + export module CloudFormation { + + export interface CancelUpdateStackParams { + StackName: string; + } + + export interface ContinueUpdateRollbackParams { + StackName: string; + } + + export interface CreateChangeSetParams { + StackName: string; + TemplateBody?: string; // specify either TemplateBody or TemplateURL + TemplateURL?: string; // specify either TemplateBody or TemplateURL + UsePreviousTemplate?: boolean; + Parameters?: CloudFormation.Parameter[]; + Capabilities?: string[]; // CAPABILITY_IAM | CAPABILITY_NAMED_IAM + ResourceTypes?: string[]; + NotificationARNs?: string[]; + Tags?: CloudFormation.Tag[]; + ChangeSetName: string; + ClientToken?: string; + Description?: string; + } + + export interface CreateStackParams { + StackName: string; + TemplateBody?: string; // specify either TemplateBody or TemplateURL + TemplateURL?: string; // specify either TemplateBody or TemplateURL + Parameters?: CloudFormation.Parameter[]; + DisableRollback?: boolean; // cannot specify both DisableRollback and OnFailure + TimeoutInMinutes?: number; + NotificationARNs?: string[]; + Capabilities?: string[]; + ResourceTypes?: string[]; + OnFailure?: string[]; // cannot specify both DisableRollback and OnFailure + // DO_NOTHING | ROLLBACK | DELETE + StackPolicyBody?: string[]; // cannot specify both StackPolicyBody and StackPolicyURL + StackPolicyURL?: string[]; // cannot specify both StackPolicyBody and StackPolicyURL + Tags?: CloudFormation.Tag[]; + } + + export interface DeleteChangeSetParams { + ChangeSetName: string; + StackName?: string; + } + + export interface DeleteStackParams { + StackName: string; + RetainResources?: string[]; + } + + export interface DescribeAccountLimitsParams { + NextToken?: string; + } + + export interface DescribeChangeSetParams { + ChangeSetName: string; + StackName?: string; + NextToken?: string; + } + + export interface DescribeStackEventsParams { + StackName?: string; + NextToken?: string; + } + + export interface DescribeStackResourceParams { + StackName: string; + LogicalResourceId: string; + } + + export interface DescribeStackResourcesParams { + StackName?: string; // must specify either StackName or PhysicalResourceId + LogicalResourceId?: string; + PhysicalResourceId?: string; // must specify either StackName or PhysicalResourceId + } + + export interface DescribeStacksParams { + StackName?: string; + NextToken?: string; + } + + export interface EstimateTemplateCostParams { + TemplateBody?: string; // must specify either TemplateBody or TemplateURL + // if both are passed, only TemplateBody is used + TemplateURL?: string; // must specify either TemplateBody or TemplateURL + Parameters?: CloudFormation.Parameter[]; + } + + export interface ExecuteChangeSetParams { + ChangeSetName: string; + StackName?: string; + } + + export interface GetStackPolicyParams { + StackName: string; + } + + export interface GetTemplateParams { + StackName: string; + } + + export interface GetTemplateSummaryParams { + // must specify one of the three + TemplateBody?: string; + TemplateURL?: string; + StackName?: string; + } + + export interface ListChangeSetsParams { + StackName: string; + NextToken?: string; + } + + export interface ListStackResourcesParams { + StackName: string; + NextToken?: string; + } + + export interface ListStacksParams { + NextToken?: string; + StackStatusFilter?: string[]; + } + + export interface SetStackPolicyParams { + StackName: string; + StackPolicyBody?: string; // cannot set both StackPolicyBody and StackPolicyURL + StackPolicyURL?: string; // cannot set both StackPolicyBody and StackPolicyURL + } + + export interface SignalResourceParams { + StackName: string; + LogicalResourceId: string; + UniqueId: string; + Status: string; // SUCCESS | FAILURE + } + + export interface UpdateStackParams { + StackName: string; + TemplateBody?: string; // specify either TemplateBody or TemplateURL, not both + TemplateURL?: string; // specify either TemplateBody or TemplateURL, not both + UsePreviousTemplate?: boolean; + StackPolicyDuringUpdateBody?: string; // cannot set both StackPolicyDuringUpdateBody and StackPolicyDuringUpdateURL + StackPolicyDuringUpdateURL?: string; // cannot set both StackPolicyDuringUpdateBody and StackPolicyDuringUpdateURL + Parameters?: CloudFormation.Parameter[]; + Capabilities?: string[]; // CAPABILITY_IAM | CAPABILITY_NAMED_IAM + ResourceTypes?: string[]; + StackPolicyBody?: string; // cannot set both StackPolicyBody and StackPolicyURL + StackPolicyURL?: string; // cannot set both StackPolicyBody and StackPolicyURL + NotificationARNs?: string[]; + Tags?: CloudFormation.Tag[]; + } + + export interface ValidateTemplateParams { + TemplateBody?: string; // must pass either TemplateBody or TemplateURL + // if both are specified, only TemplateBody is used + TemplateURL?: string; // must pass either TemplateBody or TemplateURL + } + + export interface WaitForParams { + StackName: string; + NextToken?: string; + } + + export interface Options { + params?: any; + endpoint?: string; + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: any; + credentials?: any; + credentialProvider?: any; + region?: string; + maxRetries?: number; + maxRedirects?: number; + sslEnabled?: boolean; + paramValidation?: any; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + correctClockSkew?: boolean; + s3ForcePathStyle?: boolean; + s3BucketEndpoint?: boolean; + s3DisableBodySigning?: boolean; + retryDelayOptions?: any; + httpOptions?: any; + apiVersion?: any; + apiVersions?: any; + logger?: any; + systemClockOffset?: number; + signatureVersion?: string; + signatureCache?: boolean; + } + + export interface Parameter { + ParameterKey: string; + ParameterValue: string; + UsePreviousValue?: boolean; // if you specify true, do not specify ParameterValue + } + + export interface Tag { + Key: string; + Value: string; + } + } + + // =========================================================== + export module Lambda { export interface AddPermissionParams { From 3636b4436eb3f76101c1991ed1a83d855aeca0ec Mon Sep 17 00:00:00 2001 From: hanjung Date: Mon, 22 Aug 2016 20:53:57 -0700 Subject: [PATCH 103/844] Adding OneNoteApi 1.1 --- office-js/office-js.d.ts | 2173 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 2173 insertions(+) diff --git a/office-js/office-js.d.ts b/office-js/office-js.d.ts index f2bebfe3da..f69f4a531f 100644 --- a/office-js/office-js.d.ts +++ b/office-js/office-js.d.ts @@ -13086,3 +13086,2176 @@ declare namespace Office { } } +declare namespace OneNote { + /** + * + * Represents the top-level object that contains all globally addressable OneNote objects such as notebooks, the active notebook, and the active section. + * + * [Api set: OneNoteApi 1.1] + */ + class Application extends OfficeExtension.ClientObject { + private m_notebooks; + /** + * + * Gets the collection of notebooks that are open in the OneNote application instance. In OneNote Online, only one notebook at a time is open in the application instance. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + notebooks: OneNote.NotebookCollection; + /** + * + * Gets the active notebook if one exists. If no notebook is active, throws ItemNotFound. + * + * [Api set: OneNoteApi 1.1] + */ + getActiveNotebook(): OneNote.Notebook; + /** + * + * Gets the active notebook if one exists. If no notebook is active, returns null. + * + * [Api set: OneNoteApi 1.1] + */ + getActiveNotebookOrNull(): OneNote.Notebook; + /** + * + * Gets the active outline if one exists, If no outline is active, throws ItemNotFound. + * + * [Api set: OneNoteApi 1.1] + */ + getActiveOutline(): OneNote.Outline; + /** + * + * Gets the active outline if one exists, otherwise returns null. + * + * [Api set: OneNoteApi 1.1] + */ + getActiveOutlineOrNull(): OneNote.Outline; + /** + * + * Gets the active page if one exists. If no page is active, throws ItemNotFound. + * + * [Api set: OneNoteApi 1.1] + */ + getActivePage(): OneNote.Page; + /** + * + * Gets the active page if one exists. If no page is active, returns null. + * + * [Api set: OneNoteApi 1.1] + */ + getActivePageOrNull(): OneNote.Page; + /** + * + * Gets the active section if one exists. If no section is active, throws ItemNotFound. + * + * [Api set: OneNoteApi 1.1] + */ + getActiveSection(): OneNote.Section; + /** + * + * Gets the active section if one exists. If no section is active, returns null. + * + * [Api set: OneNoteApi 1.1] + */ + getActiveSectionOrNull(): OneNote.Section; + /** + * + * Opens the specified page in the application instance. + * + * @param page The page to open. + * + * [Api set: OneNoteApi 1.1] + */ + navigateToPage(page: OneNote.Page): void; + /** + * + * Gets the specified page, and opens it in the application instance. + * + * @param url The client url of the page to open. + * + * [Api set: OneNoteApi 1.1] + */ + navigateToPageWithClientUrl(url: string): OneNote.Page; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Application; + } + /** + * + * Represents ink analysis data for a given set of ink strokes. + * + * [Api set: OneNoteApi 1.1] + */ + class InkAnalysis extends OfficeExtension.ClientObject { + private m_id; + private m_page; + private m_paragraphs; + private m__ReferenceId; + /** + * + * Gets the parent page object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + page: OneNote.Page; + /** + * + * Gets the ink analysis paragraphs in this page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraphs: OneNote.InkAnalysisParagraphCollection; + /** + * + * Gets the ID of the InkAnalysis object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkAnalysis; + } + /** + * + * Represents ink analysis data for an identified paragraph formed by ink strokes. + * + * [Api set: OneNoteApi 1.1] + */ + class InkAnalysisParagraph extends OfficeExtension.ClientObject { + private m_id; + private m_inkAnalysis; + private m_lines; + private m__ReferenceId; + /** + * + * Reference to the parent InkAnalysisPage. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + inkAnalysis: OneNote.InkAnalysis; + /** + * + * Gets the ink analysis lines in this ink analysis paragraph. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + lines: OneNote.InkAnalysisLineCollection; + /** + * + * Gets the ID of the InkAnalysisParagraph object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkAnalysisParagraph; + } + /** + * + * Represents a collection of InkAnalysisParagraph objects. + * + * [Api set: OneNoteApi 1.1] + */ + class InkAnalysisParagraphCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of InkAnalysisParagraphs in the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a InkAnalysisParagraph object by ID or by its index in the collection. Read-only. + * + * @param index The ID of the InkAnalysisParagraph object, or the index location of the InkAnalysisParagraph object in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.InkAnalysisParagraph; + /** + * + * Gets a InkAnalysisParagraph on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.InkAnalysisParagraph; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkAnalysisParagraphCollection; + } + /** + * + * Represents ink analysis data for an identified text line formed by ink strokes. + * + * [Api set: OneNoteApi 1.1] + */ + class InkAnalysisLine extends OfficeExtension.ClientObject { + private m_id; + private m_paragraph; + private m_words; + private m__ReferenceId; + /** + * + * Reference to the parent InkAnalysisParagraph. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraph: OneNote.InkAnalysisParagraph; + /** + * + * Gets the ink analysis words in this ink analysis line. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + words: OneNote.InkAnalysisWordCollection; + /** + * + * Gets the ID of the InkAnalysisLine object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkAnalysisLine; + } + /** + * + * Represents a collection of InkAnalysisLine objects. + * + * [Api set: OneNoteApi 1.1] + */ + class InkAnalysisLineCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of InkAnalysisLines in the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a InkAnalysisLine object by ID or by its index in the collection. Read-only. + * + * @param index The ID of the InkAnalysisLine object, or the index location of the InkAnalysisLine object in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.InkAnalysisLine; + /** + * + * Gets a InkAnalysisLine on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.InkAnalysisLine; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkAnalysisLineCollection; + } + /** + * + * Represents ink analysis data for an identified word formed by ink strokes. + * + * [Api set: OneNoteApi 1.1] + */ + class InkAnalysisWord extends OfficeExtension.ClientObject { + private m_id; + private m_languageId; + private m_line; + private m_strokePointers; + private m_wordAlternates; + private m__ReferenceId; + /** + * + * Reference to the parent InkAnalysisLine. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + line: OneNote.InkAnalysisLine; + /** + * + * Gets the ID of the InkAnalysisWord object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * The id of the recognized language in this inkAnalysisWord. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + languageId: string; + /** + * + * Weak references to the ink strokes that were recognized as part of this ink analysis word. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + strokePointers: Array; + /** + * + * The words that were recognized in this ink word, in order of likelihood. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + wordAlternates: Array; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkAnalysisWord; + } + /** + * + * Represents a collection of InkAnalysisWord objects. + * + * [Api set: OneNoteApi 1.1] + */ + class InkAnalysisWordCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of InkAnalysisWords in the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a InkAnalysisWord object by ID or by its index in the collection. Read-only. + * + * @param index The ID of the InkAnalysisWord object, or the index location of the InkAnalysisWord object in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.InkAnalysisWord; + /** + * + * Gets a InkAnalysisWord on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.InkAnalysisWord; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkAnalysisWordCollection; + } + /** + * + * Represents a group of ink strokes. + * + * [Api set: OneNoteApi 1.1] + */ + class FloatingInk extends OfficeExtension.ClientObject { + private m_id; + private m_inkStrokes; + private m_pageContent; + private m__ReferenceId; + /** + * + * Gets the strokes of the FloatingInk object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + inkStrokes: OneNote.InkStrokeCollection; + /** + * + * Gets the PageContent parent of the FloatingInk object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + pageContent: OneNote.PageContent; + /** + * + * Gets the ID of the FloatingInk object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.FloatingInk; + } + /** + * + * Represents a single stroke of ink. + * + * [Api set: OneNoteApi 1.1] + */ + class InkStroke extends OfficeExtension.ClientObject { + private m_floatingInk; + private m_id; + private m__ReferenceId; + /** + * + * Gets the ID of the InkStroke object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + floatingInk: OneNote.FloatingInk; + /** + * + * Gets the ID of the InkStroke object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkStroke; + } + /** + * + * Represents a collection of InkStroke objects. + * + * [Api set: OneNoteApi 1.1] + */ + class InkStrokeCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of InkStrokes in the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a InkStroke object by ID or by its index in the collection. Read-only. + * + * @param index The ID of the InkStroke object, or the index location of the InkStroke object in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.InkStroke; + /** + * + * Gets a InkStroke on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.InkStroke; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkStrokeCollection; + } + /** + * + * A container for the ink in a word in a paragraph. + * + * [Api set: OneNoteApi 1.1] + */ + class InkWord extends OfficeExtension.ClientObject { + private m_id; + private m_languageId; + private m_paragraph; + private m_wordAlternates; + private m__ReferenceId; + /** + * + * The parent paragraph containing the ink word. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraph: OneNote.Paragraph; + /** + * + * Gets the ID of the InkWord object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * The id of the recognized language in this ink word. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + languageId: string; + /** + * + * The words that were recognized in this ink word, in order of likelihood. Read-only. + * + * [Api set: OneNoteApi] + */ + wordAlternates: Array; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkWord; + } + /** + * + * Represents a collection of InkWord objects. + * + * [Api set: OneNoteApi 1.1] + */ + class InkWordCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of InkWords in the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a InkWord object by ID or by its index in the collection. Read-only. + * + * @param index The ID of the InkWord object, or the index location of the InkWord object in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.InkWord; + /** + * + * Gets a InkWord on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.InkWord; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.InkWordCollection; + } + /** + * + * Represents a OneNote notebook. Notebooks contain section groups and sections. + * + * [Api set: OneNoteApi 1.1] + */ + class Notebook extends OfficeExtension.ClientObject { + private m_clientUrl; + private m_id; + private m_name; + private m_sectionGroups; + private m_sections; + private m__ReferenceId; + /** + * + * The section groups in the notebook. Read only + * + * [Api set: OneNoteApi 1.1] + */ + sectionGroups: OneNote.SectionGroupCollection; + /** + * + * The the sections of the notebook. Read only + * + * [Api set: OneNoteApi 1.1] + */ + sections: OneNote.SectionCollection; + /** + * + * The client url of the notebook. Read only + * + * [Api set: OneNoteApi 1.1] + */ + clientUrl: string; + /** + * + * Gets the ID of the notebook. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the name of the notebook. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + name: string; + /** + * + * Adds a new section to the end of the notebook. + * + * @param name The name of the new section. + * + * [Api set: OneNoteApi 1.1] + */ + addSection(name: string): OneNote.Section; + /** + * + * Adds a new section group to the end of the notebook. + * + * @param name The name of the new section. + * + * [Api set: OneNoteApi 1.1] + */ + addSectionGroup(name: string): OneNote.SectionGroup; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Notebook; + } + /** + * + * Represents a collection of notebooks. + * + * [Api set: OneNoteApi 1.1] + */ + class NotebookCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of notebooks in the collection. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets the collection of notebooks with the specified name that are open in the application instance. + * + * @param name The name of the notebook. + * + * [Api set: OneNoteApi 1.1] + */ + getByName(name: string): OneNote.NotebookCollection; + /** + * + * Gets a notebook by ID or by its index in the collection. Read-only. + * + * @param index The ID of the notebook, or the index location of the notebook in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.Notebook; + /** + * + * Gets a notebook on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.Notebook; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.NotebookCollection; + } + /** + * + * Represents a OneNote section group. Section groups can contain sections and other section groups. + * + * [Api set: OneNoteApi 1.1] + */ + class SectionGroup extends OfficeExtension.ClientObject { + private m_clientUrl; + private m_id; + private m_name; + private m_notebook; + private m_parentSectionGroup; + private m_parentSectionGroupOrNull; + private m_sectionGroups; + private m_sections; + private m__ReferenceId; + /** + * + * Gets the notebook that contains the section group. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + notebook: OneNote.Notebook; + /** + * + * Gets the section group that contains the section group. Throws ItemNotFound if the section group is a direct child of the notebook. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentSectionGroup: OneNote.SectionGroup; + /** + * + * Gets the section group that contains the section group. Returns null if the section group is a direct child of the notebook. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentSectionGroupOrNull: OneNote.SectionGroup; + /** + * + * The collection of section groups in the section group. Read only + * + * [Api set: OneNoteApi 1.1] + */ + sectionGroups: OneNote.SectionGroupCollection; + /** + * + * The collection of sections in the section group. Read only + * + * [Api set: OneNoteApi 1.1] + */ + sections: OneNote.SectionCollection; + /** + * + * The client url of the section group. Read only + * + * [Api set: OneNoteApi 1.1] + */ + clientUrl: string; + /** + * + * Gets the ID of the section group. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the name of the section group. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + name: string; + /** + * + * Adds a new section to the end of the section group. + * + * @param title The name of the new section. + * + * [Api set: OneNoteApi 1.1] + */ + addSection(title: string): OneNote.Section; + /** + * + * Adds a new section group to the end of this sectionGroup. + * + * @param name The name of the new section. + * + * [Api set: OneNoteApi 1.1] + */ + addSectionGroup(name: string): OneNote.SectionGroup; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.SectionGroup; + } + /** + * + * Represents a collection of section groups. + * + * [Api set: OneNoteApi 1.1] + */ + class SectionGroupCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of section groups in the collection. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets the collection of section groups with the specified name. + * + * @param name The name of the section group. + * + * [Api set: OneNoteApi 1.1] + */ + getByName(name: string): OneNote.SectionGroupCollection; + /** + * + * Gets a section group by ID or by its index in the collection. Read-only. + * + * @param index The ID of the section group, or the index location of the section group in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.SectionGroup; + /** + * + * Gets a section group on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.SectionGroup; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.SectionGroupCollection; + } + /** + * + * Represents a OneNote section. Sections can contain pages. + * + * [Api set: OneNoteApi 1.1] + */ + class Section extends OfficeExtension.ClientObject { + private m_clientUrl; + private m_id; + private m_name; + private m_notebook; + private m_pages; + private m_parentSectionGroup; + private m_parentSectionGroupOrNull; + private m__ReferenceId; + /** + * + * Gets the notebook that contains the section. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + notebook: OneNote.Notebook; + /** + * + * The collection of pages in the section. Read only + * + * [Api set: OneNoteApi 1.1] + */ + pages: OneNote.PageCollection; + /** + * + * Gets the section group that contains the section. Throws ItemNotFound if the section is a direct child of the notebook. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentSectionGroup: OneNote.SectionGroup; + /** + * + * Gets the section group that contains the section. Returns null if the section is a direct child of the notebook. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentSectionGroupOrNull: OneNote.SectionGroup; + /** + * + * The client url of the section. Read only + * + * [Api set: OneNoteApi 1.1] + */ + clientUrl: string; + /** + * + * Gets the ID of the section. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the name of the section. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + name: string; + /** + * + * Adds a new page to the end of the section. + * + * @param title The title of the new page. + * + * [Api set: OneNoteApi 1.1] + */ + addPage(title: string): OneNote.Page; + /** + * + * Copies this section to specified notebook. + * + * @param destinationNotebook The notebook to copy this section to. + * + * [Api set: OneNoteApi 1.1] + */ + copyToNotebook(destinationNotebook: OneNote.Notebook): OneNote.Section; + /** + * + * Copies this section to specified section group. + * + * @param destinationSectionGroup The section group to copy this section to. + * + * [Api set: OneNoteApi 1.1] + */ + copyToSectionGroup(destinationSectionGroup: OneNote.SectionGroup): OneNote.Section; + /** + * + * Inserts a new section before or after the current section. + * + * @param location The location of the new section relative to the current section. + * @param title The name of the new section. + * + * [Api set: OneNoteApi 1.1] + */ + insertSectionAsSibling(location: string, title: string): OneNote.Section; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Section; + } + /** + * + * Represents a collection of sections. + * + * [Api set: OneNoteApi 1.1] + */ + class SectionCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of sections in the collection. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets the collection of sections with the specified name. + * + * @param name The name of the section. + * + * [Api set: OneNoteApi 1.1] + */ + getByName(name: string): OneNote.SectionCollection; + /** + * + * Gets a section by ID or by its index in the collection. Read-only. + * + * @param index The ID of the section, or the index location of the section in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.Section; + /** + * + * Gets a section on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.Section; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.SectionCollection; + } + /** + * + * Represents a OneNote page. + * + * [Api set: OneNoteApi 1.1] + */ + class Page extends OfficeExtension.ClientObject { + private m_clientUrl; + private m_contents; + private m_id; + private m_inkAnalysisOrNull; + private m_pageLevel; + private m_parentSection; + private m_title; + private m_webUrl; + private m__ReferenceId; + /** + * + * The collection of PageContent objects on the page. Read only + * + * [Api set: OneNoteApi 1.1] + */ + contents: OneNote.PageContentCollection; + /** + * + * Text interpretation for the ink on the page. Returns null if there is no ink analysis information. Read only. + * + * [Api set: OneNoteApi 1.1] + */ + inkAnalysisOrNull: OneNote.InkAnalysis; + /** + * + * Gets the section that contains the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentSection: OneNote.Section; + /** + * + * The client url of the page. Read only + * + * [Api set: OneNoteApi 1.1] + */ + clientUrl: string; + /** + * + * Gets the ID of the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets or sets the indentation level of the page. + * + * [Api set: OneNoteApi 1.1] + */ + pageLevel: number; + /** + * + * Gets or sets the title of the page. + * + * [Api set: OneNoteApi 1.1] + */ + title: string; + /** + * + * The web url of the page. Read only + * + * [Api set: OneNoteApi 1.1] + */ + webUrl: string; + /** + * + * Adds an Outline to the page at the specified position. + * + * @param left The left position of the top, left corner of the Outline. + * @param top The top position of the top, left corner of the Outline. + * @param html An HTML string that describes the visual presentation of the Outline. See [supported HTML](../../docs/onenote/onenote-add-ins-page-content.md#supported-html) for the OneNote add-ins JavaScript API. + * + * [Api set: OneNoteApi 1.1] + */ + addOutline(left: number, top: number, html: string): OneNote.Outline; + /** + * + * Copies this page to specified section. + * + * @param destinationSection The section to copy this page to. + * + * [Api set: OneNoteApi 1.1] + */ + copyToSection(destinationSection: OneNote.Section): OneNote.Page; + /** + * + * Inserts a new page before or after the current page. + * + * @param location The location of the new page relative to the current page. + * @param title The title of the new page. + * + * [Api set: OneNoteApi 1.1] + */ + insertPageAsSibling(location: string, title: string): OneNote.Page; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Page; + } + /** + * + * Represents a collection of pages. + * + * [Api set: OneNoteApi 1.1] + */ + class PageCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of pages in the collection. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets the collection of pages with the specified title. + * + * @param title The title of the page. + * + * [Api set: OneNoteApi 1.1] + */ + getByTitle(title: string): OneNote.PageCollection; + /** + * + * Gets a page by ID or by its index in the collection. Read-only. + * + * @param index The ID of the page, or the index location of the page in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.Page; + /** + * + * Gets a page on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.Page; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.PageCollection; + } + /** + * + * Represents a region on a page that contains top-level content types such as Outline or Image. A PageContent object can be assigned an XY position. + * + * [Api set: OneNoteApi 1.1] + */ + class PageContent extends OfficeExtension.ClientObject { + private m_id; + private m_image; + private m_ink; + private m_left; + private m_outline; + private m_parentPage; + private m_top; + private m_type; + private m__ReferenceId; + /** + * + * Gets the Image in the PageContent object. Throws an exception if PageContentType is not Image. + * + * [Api set: OneNoteApi 1.1] + */ + image: OneNote.Image; + /** + * + * Gets the ink in the PageContent object. Throws an exception if PageContentType is not Ink. + * + * [Api set: OneNoteApi 1.1] + */ + ink: OneNote.FloatingInk; + /** + * + * Gets the Outline in the PageContent object. Throws an exception if PageContentType is not Outline. + * + * [Api set: OneNoteApi 1.1] + */ + outline: OneNote.Outline; + /** + * + * Gets the page that contains the PageContent object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentPage: OneNote.Page; + /** + * + * Gets the ID of the PageContent object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets or sets the left (X-axis) position of the PageContent object. + * + * [Api set: OneNoteApi 1.1] + */ + left: number; + /** + * + * Gets or sets the top (Y-axis) position of the PageContent object. + * + * [Api set: OneNoteApi 1.1] + */ + top: number; + /** + * + * Gets the type of the PageContent object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + type: string; + /** + * + * Deletes the PageContent object. + * + * [Api set: OneNoteApi 1.1] + */ + delete(): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.PageContent; + } + /** + * + * Represents the contents of a page, as a collection of PageContent objects. + * + * [Api set: OneNoteApi 1.1] + */ + class PageContentCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of page contents in the collection. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a PageContent object by ID or by its index in the collection. Read-only. + * + * @param index The ID of the PageContent object, or the index location of the PageContent object in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.PageContent; + /** + * + * Gets a page content on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.PageContent; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.PageContentCollection; + } + /** + * + * Represents a container for Paragraph objects. + * + * [Api set: OneNoteApi 1.1] + */ + class Outline extends OfficeExtension.ClientObject { + private m_id; + private m_pageContent; + private m_paragraphs; + private m__ReferenceId; + /** + * + * Gets the PageContent object that contains the Outline. This object defines the position of the Outline on the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + pageContent: OneNote.PageContent; + /** + * + * Gets the collection of Paragraph objects in the Outline. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraphs: OneNote.ParagraphCollection; + /** + * + * Gets the ID of the Outline object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Adds the specified HTML to the bottom of the Outline. + * + * @param html The HTML string to append. See [supported HTML](../../docs/onenote/onenote-add-ins-page-content.md#supported-html) for the OneNote add-ins JavaScript API. + * + * [Api set: OneNoteApi 1.1] + */ + appendHtml(html: string): void; + /** + * + * Adds the specified image to the bottom of the Outline. + * + * @param base64EncodedImage HTML string to append. + * @param width Optional. Width in the unit of Points. The default value is null and image width will be respected. + * @param height Optional. Height in the unit of Points. The default value is null and image height will be respected. + * + * [Api set: OneNoteApi 1.1] + */ + appendImage(base64EncodedImage: string, width: number, height: number): OneNote.Image; + /** + * + * Adds the specified text to the bottom of the Outline. + * + * @param paragraphText HTML string to append. + * + * [Api set: OneNoteApi 1.1] + */ + appendRichText(paragraphText: string): OneNote.RichText; + /** + * + * Adds a table with the specified number of rows and columns to the bottom of the outline. + * + * @param rowCount Required. The number of rows in the table. + * @param columnCount Required. The number of columns in the table. + * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. + * + * [Api set: OneNoteApi 1.1] + */ + appendTable(rowCount: number, columnCount: number, values?: Array>): OneNote.Table; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Outline; + } + /** + * + * A container for the visible content on a page. A Paragraph can contain any one ParagraphType type of content. + * + * [Api set: OneNoteApi 1.1] + */ + class Paragraph extends OfficeExtension.ClientObject { + private m_id; + private m_image; + private m_inkWords; + private m_outline; + private m_paragraphs; + private m_parentParagraph; + private m_parentParagraphOrNull; + private m_parentTableCell; + private m_parentTableCellOrNull; + private m_richText; + private m_table; + private m_type; + private m__ReferenceId; + /** + * + * Gets the Image object in the Paragraph. Throws an exception if ParagraphType is not Image. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + image: OneNote.Image; + /** + * + * Gets the Ink collection in the Paragraph. Throws an exception if ParagraphType is not Ink. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + inkWords: OneNote.InkWordCollection; + /** + * + * Gets the Outline object that contains the Paragraph. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + outline: OneNote.Outline; + /** + * + * The collection of paragraphs under this paragraph. Read only + * + * [Api set: OneNoteApi 1.1] + */ + paragraphs: OneNote.ParagraphCollection; + /** + * + * Gets the parent paragraph object. Throws if a parent paragraph does not exist. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentParagraph: OneNote.Paragraph; + /** + * + * Gets the parent paragraph object. Returns null if a parent paragraph does not exist. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentParagraphOrNull: OneNote.Paragraph; + /** + * + * Gets the TableCell object that contains the Paragraph if one exists. If parent is not a TableCell, throws ItemNotFound. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentTableCell: OneNote.TableCell; + /** + * + * Gets the TableCell object that contains the Paragraph if one exists. If parent is not a TableCell, returns null. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentTableCellOrNull: OneNote.TableCell; + /** + * + * Gets the RichText object in the Paragraph. Throws an exception if ParagraphType is not RichText. Read-only + * + * [Api set: OneNoteApi 1.1] + */ + richText: OneNote.RichText; + /** + * + * Gets the Table object in the Paragraph. Throws an exception if ParagraphType is not Table. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + table: OneNote.Table; + /** + * + * Gets the ID of the Paragraph object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the type of the Paragraph object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + type: string; + /** + * + * Deletes the paragraph + * + * [Api set: OneNoteApi 1.1] + */ + delete(): void; + /** + * + * Inserts the specified HTML content + * + * @param insertLocation The location of new contents relative to the current Paragraph. + * @param html An HTML string that describes the visual presentation of the content. See [supported HTML](../../docs/onenote/onenote-add-ins-page-content.md#supported-html) for the OneNote add-ins JavaScript API. + * + * [Api set: OneNoteApi 1.1] + */ + insertHtmlAsSibling(insertLocation: string, html: string): void; + /** + * + * Inserts the image at the specified insert location.. + * + * @param insertLocation The location of the table relative to the current Paragraph. + * @param base64EncodedImage HTML string to append. + * @param width Optional. Width in the unit of Points. The default value is null and image width will be respected. + * @param height Optional. Height in the unit of Points. The default value is null and image height will be respected. + * + * [Api set: OneNoteApi 1.1] + */ + insertImageAsSibling(insertLocation: string, base64EncodedImage: string, width: number, height: number): OneNote.Image; + /** + * + * Inserts the paragraph text at the specifiec insert location. + * + * @param insertLocation The location of the table relative to the current Paragraph. + * @param paragraphText HTML string to append. + * + * [Api set: OneNoteApi 1.1] + */ + insertRichTextAsSibling(insertLocation: string, paragraphText: string): OneNote.RichText; + /** + * + * Adds a table with the specified number of rows and columns before or after the current paragraph. + * + * @param insertLocation The location of the table relative to the current Paragraph. + * @param rowCount The number of rows in the table. + * @param columnCount The number of columns in the table. + * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. + * + * [Api set: OneNoteApi 1.1] + */ + insertTableAsSibling(insertLocation: string, rowCount: number, columnCount: number, values?: Array>): OneNote.Table; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Paragraph; + } + /** + * + * Represents a collection of Paragraph objects. + * + * [Api set: OneNoteApi 1.1] + */ + class ParagraphCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of paragraphs in the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a Paragraph object by ID or by its index in the collection. Read-only. + * + * @param index The ID of the Paragraph object, or the index location of the Paragraph object in the collection. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.Paragraph; + /** + * + * Gets a paragraph on its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.Paragraph; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.ParagraphCollection; + } + /** + * + * Represents a RichText object in a Paragraph. + * + * [Api set: OneNoteApi 1.1] + */ + class RichText extends OfficeExtension.ClientObject { + private m_id; + private m_paragraph; + private m_text; + private m__ReferenceId; + /** + * + * Gets the Paragraph object that contains the RichText object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraph: OneNote.Paragraph; + /** + * + * Gets the ID of the RichText object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the text content of the RichText object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + text: string; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.RichText; + } + /** + * + * Represents an Image. An Image can be a direct child of a PageContent object or a Paragraph object. + * + * [Api set: OneNoteApi 1.1] + */ + class Image extends OfficeExtension.ClientObject { + private m_description; + private m_height; + private m_hyperlink; + private m_id; + private m_ocrData; + private m_pageContent; + private m_paragraph; + private m_width; + private m__ReferenceId; + /** + * + * Gets the PageContent object that contains the Image. Throws if the Image is not a direct child of a PageContent. This object defines the position of the Image on the page. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + pageContent: OneNote.PageContent; + /** + * + * Gets the Paragraph object that contains the Image. Throws if the Image is not a direct child of a Paragraph. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraph: OneNote.Paragraph; + /** + * + * Gets or sets the description of the Image. + * + * [Api set: OneNoteApi 1.1] + */ + description: string; + /** + * + * Gets or sets the height of the Image layout. + * + * [Api set: OneNoteApi 1.1] + */ + height: number; + /** + * + * Gets or sets the hyperlink of the Image. + * + * [Api set: OneNoteApi 1.1] + */ + hyperlink: string; + /** + * + * Gets the ID of the Image object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the data obtained by OCR (Optical Character Recognition) of this Image, such as OCR text and language. + * + * [Api set: OneNoteApi 1.1] + */ + ocrData: OneNote.ImageOcrData; + /** + * + * Gets or sets the width of the Image layout. + * + * [Api set: OneNoteApi 1.1] + */ + width: number; + /** + * + * Gets the base64-encoded binary representation of the Image. + Example: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA... + * + * [Api set: OneNoteApi 1.1] + */ + getBase64Image(): OfficeExtension.ClientResult; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Image; + } + /** + * + * Represents a table in a OneNote page. + * + * [Api set: OneNoteApi 1.1] + */ + class Table extends OfficeExtension.ClientObject { + private m_borderVisible; + private m_columnCount; + private m_id; + private m_paragraph; + private m_rowCount; + private m_rows; + private m__ReferenceId; + /** + * + * Gets the Paragraph object that contains the Table object. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraph: OneNote.Paragraph; + /** + * + * Gets all of the table rows. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + rows: OneNote.TableRowCollection; + /** + * + * Gets or sets whether the borders are visible or not. True if they are visible, false if they are hidden. + * + * [Api set: OneNoteApi 1.1] + */ + borderVisible: boolean; + /** + * + * Gets the number of columns in the table. + * + * [Api set: OneNoteApi 1.1] + */ + columnCount: number; + /** + * + * Gets the ID of the table. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the number of rows in the table. + * + * [Api set: OneNoteApi 1.1] + */ + rowCount: number; + /** + * + * Adds a column to the end of the table. Values, if specified, are set in the new column. Otherwise the column is empty. + * + * @param values Optional. Strings to insert in the new column, specified as an array. Must not have more values than rows in the table. + * + * [Api set: OneNoteApi 1.1] + */ + appendColumn(values?: Array): void; + /** + * + * Adds a row to the end of the table. Values, if specified, are set in the new row. Otherwise the row is empty. + * + * @param values Optional. Strings to insert in the new row, specified as an array. Must not have more values than columns in the table. + * + * [Api set: OneNoteApi 1.1] + */ + appendRow(values?: Array): OneNote.TableRow; + /** + * + * Clears the contents of the table. + * + * [Api set: OneNoteApi 1.1] + */ + clear(): void; + /** + * + * Gets the table cell at a specified row and column. + * + * @param rowIndex The index of the row. + * @param cellIndex The index of the cell in the row. + * + * [Api set: OneNoteApi 1.1] + */ + getCell(rowIndex: number, cellIndex: number): OneNote.TableCell; + /** + * + * Inserts a column at the given index in the table. Values, if specified, are set in the new column. Otherwise the column is empty. + * + * @param index Index where the column will be inserted in the table. + * @param values Optional. Strings to insert in the new column, specified as an array. Must not have more values than rows in the table. + * + * [Api set: OneNoteApi 1.1] + */ + insertColumn(index: number, values?: Array): void; + /** + * + * Inserts a row at the given index in the table. Values, if specified, are set in the new row. Otherwise the row is empty. + * + * @param index Index where the row will be inserted in the table. + * @param values Optional. Strings to insert in the new row, specified as an array. Must not have more values than columns in the table. + * + * [Api set: OneNoteApi 1.1] + */ + insertRow(index: number, values?: Array): OneNote.TableRow; + setShadingColor(colorCode: string): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.Table; + } + /** + * + * Represents a row in a table. + * + * [Api set: OneNoteApi 1.1] + */ + class TableRow extends OfficeExtension.ClientObject { + private m_cellCount; + private m_cells; + private m_id; + private m_parentTable; + private m_rowIndex; + private m__ReferenceId; + /** + * + * Gets the cells in the row. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + cells: OneNote.TableCellCollection; + /** + * + * Gets the parent table. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentTable: OneNote.Table; + /** + * + * Gets the number of cells in the row. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + cellCount: number; + /** + * + * Gets the ID of the row. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the index of the row in its parent table. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + rowIndex: number; + /** + * + * Clears the contents of the row. + * + * [Api set: OneNoteApi 1.1] + */ + clear(): void; + /** + * + * Inserts a row before or after the current row. + * + * @param insertLocation Where the new rows should be inserted relative to the current row. + * @param values Strings to insert in the new row, specified as an array. Must not have more cells than in the current row. Optional. + * + * [Api set: OneNoteApi 1.1] + */ + insertRowAsSibling(insertLocation: string, values?: Array): OneNote.TableRow; + setShadingColor(colorCode: string): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.TableRow; + } + /** + * + * Contains a collection of TableRow objects. + * + * [Api set: OneNoteApi 1.1] + */ + class TableRowCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of table rows in this collection. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a table row object by ID or by its index in the collection. Read-only. + * + * @param index A number that identifies the index location of a table row object. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.TableRow; + /** + * + * Gets a table row at its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.TableRow; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.TableRowCollection; + } + /** + * + * Represents a cell in a OneNote table. + * + * [Api set: OneNoteApi 1.1] + */ + class TableCell extends OfficeExtension.ClientObject { + private m_cellIndex; + private m_id; + private m_paragraphs; + private m_parentRow; + private m_rowIndex; + private m_shadingColor; + private m__ReferenceId; + /** + * + * Gets the collection of Paragraph objects in the TableCell. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + paragraphs: OneNote.ParagraphCollection; + /** + * + * Gets the parent row of the cell. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + parentRow: OneNote.TableRow; + /** + * + * Gets the index of the cell in its row. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + cellIndex: number; + /** + * + * Gets the ID of the cell. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + id: string; + /** + * + * Gets the index of the cell's row in the table. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + rowIndex: number; + /** + * + * Gets and sets the shading color of the cell + * + * [Api set: OneNoteApi 1.1] + */ + shadingColor: string; + /** + * + * Adds the specified HTML to the bottom of the TableCell. + * + * @param html The HTML string to append. See [supported HTML](../../docs/onenote/onenote-add-ins-page-content.md#supported-html) for the OneNote add-ins JavaScript API. + * + * [Api set: OneNoteApi 1.1] + */ + appendHtml(html: string): void; + /** + * + * Adds the specified image to table cell. + * + * @param base64EncodedImage HTML string to append. + * @param width Optional. Width in the unit of Points. The default value is null and image width will be respected. + * @param height Optional. Height in the unit of Points. The default value is null and image height will be respected. + * + * [Api set: OneNoteApi 1.1] + */ + appendImage(base64EncodedImage: string, width: number, height: number): OneNote.Image; + /** + * + * Adds the specified text to table cell. + * + * @param paragraphText HTML string to append. + * + * [Api set: OneNoteApi 1.1] + */ + appendRichText(paragraphText: string): OneNote.RichText; + /** + * + * Adds a table with the specified number of rows and columns to table cell. + * + * @param rowCount Required. The number of rows in the table. + * @param columnCount Required. The number of columns in the table. + * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. + * + * [Api set: OneNoteApi 1.1] + */ + appendTable(rowCount: number, columnCount: number, values?: Array>): OneNote.Table; + /** + * + * Clears the contents of the cell. + * + * [Api set: OneNoteApi 1.1] + */ + clear(): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.TableCell; + } + /** + * + * Contains a collection of TableCell objects. + * + * [Api set: OneNoteApi 1.1] + */ + class TableCellCollection extends OfficeExtension.ClientObject { + private m_count; + private m__ReferenceId; + private m__items; + /** Gets the loaded child items in this collection. */ + items: Array; + /** + * + * Returns the number of tablecells in this collection. Read-only. + * + * [Api set: OneNoteApi 1.1] + */ + count: number; + /** + * + * Gets a table cell object by ID or by its index in the collection. Read-only. + * + * @param index A number that identifies the index location of a table cell object. + * + * [Api set: OneNoteApi 1.1] + */ + getItem(index: number | string): OneNote.TableCell; + /** + * + * Gets a tablecell at its position in the collection. + * + * @param index Index value of the object to be retrieved. Zero-indexed. + * + * [Api set: OneNoteApi 1.1] + */ + getItemAt(index: number): OneNote.TableCell; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): OneNote.TableCellCollection; + } + /** + * + * Represents data obtained by OCR (optical character recognition) of an image + * + * [Api set: OneNoteApi 1.1] + */ + interface ImageOcrData { + /** + * + * Represents the OCR language, with values such as EN-US + * + * [Api set: OneNoteApi 1.1] + */ + ocrLanguageId: string; + /** + * + * Represents the text obtained by OCR of the image + * + * [Api set: OneNoteApi 1.1] + */ + ocrText: string; + } + /** + * + * Weak reference to an ink stroke object and its content parent + * + * [Api set: OneNoteApi 1.1] + */ + interface InkStrokePointer { + /** + * + * Represents the id of the page content object corresponding to this stroke + * + * [Api set: OneNoteApi 1.1] + */ + contentId: string; + /** + * + * Represents the id of the ink stroke + * + * [Api set: OneNoteApi 1.1] + */ + inkStrokeId: string; + } + /** + * [Api set: OneNoteApi] + */ + module InsertLocation { + var before: string; + var after: string; + } + /** + * [Api set: OneNoteApi] + */ + module Alignment { + var left: string; + var centered: string; + var right: string; + var justified: string; + } + /** + * [Api set: OneNoteApi] + */ + module Selected { + var notSelected: string; + var partialSelected: string; + var selected: string; + } + /** + * [Api set: OneNoteApi] + */ + module PageContentType { + var outline: string; + var image: string; + var ink: string; + var other: string; + } + /** + * [Api set: OneNoteApi] + */ + module ParagraphType { + var richText: string; + var image: string; + var table: string; + var ink: string; + var other: string; + } + module ErrorCodes { + var generalException: string; + } +} +declare namespace OneNote { + class RequestContext extends OfficeExtension.ClientRequestContext { + private m_onenote; + constructor(url?: string); + application: Application; + } + /** + * Executes a batch script that performs actions on the OneNote object model. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the OneNote application. Since the Office add-in and the WoOneNote application run in two different processes, the request context is required to get access to the OneNote object model from the add-in. + */ + function run(batch: (context: OneNote.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; +} From e9fc032fe8a9cf754f2c9b06ab855bfbf837d4e6 Mon Sep 17 00:00:00 2001 From: Massimo Hamilton Date: Tue, 23 Aug 2016 08:52:49 +0100 Subject: [PATCH 104/844] Durandal - Fixes to DialogContext. See below: - Add blockoutOpacity to DialogContext - Mark name of getContext as optional All as per docs here: http://durandaljs.com/documentation/Showing-Message-Boxes-And-Modals.html#dialog-contexts --- durandal/durandal.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/durandal/durandal.d.ts b/durandal/durandal.d.ts index 97e1307a0b..1b28ca7bc3 100644 --- a/durandal/durandal.d.ts +++ b/durandal/durandal.d.ts @@ -690,6 +690,11 @@ declare module 'plugins/dialog' { * @param {object} context The composition context. */ compositionComplete(child: HTMLElement, parent: HTMLElement, context: composition.CompositionContext): void; + + /** + * Opacity of the blockout. The default is 0.6. + */ + blockoutOpacity?: number; } interface Dialog { @@ -728,7 +733,7 @@ declare module 'plugins/dialog' { * @param {string} [name] The name of the context to retrieve. * @returns {DialogContext} True context. */ - export function getContext(name: string): DialogContext; + export function getContext(name?: string): DialogContext; /** * Adds (or replaces) a dialog context. From fe5c10be966bf1949ccd2811b430b0e666ff7829 Mon Sep 17 00:00:00 2001 From: Gabriel JUCHAULT Date: Tue, 23 Aug 2016 13:27:40 +0200 Subject: [PATCH 105/844] Fix countdown types --- countdown/countdown-tests.ts | 10 +++++----- countdown/countdown.d.ts | 17 ++++++++++------- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/countdown/countdown-tests.ts b/countdown/countdown-tests.ts index c803f1acc2..3ad8890aab 100644 --- a/countdown/countdown-tests.ts +++ b/countdown/countdown-tests.ts @@ -1,15 +1,15 @@ /// -import { countdown, Timespan, CountdownStatic, Format } from 'countdown'; +import * as countdown from 'countdown'; -let ts: Timespan; +let ts: countdown.Timespan; let interval: number; -ts = countdown(new Date()); -ts = countdown(150); +ts = countdown(new Date()); +ts = countdown(150); interval = countdown(new Date(), - function (ts: Timespan) { + function (ts: countdown.Timespan) { document.getElementById('pageTimer').innerHTML = ts.toHTML('strong'); }, countdown.HOURS | countdown.MINUTES | countdown.SECONDS, diff --git a/countdown/countdown.d.ts b/countdown/countdown.d.ts index 5b40541dd0..bcb0d07976 100644 --- a/countdown/countdown.d.ts +++ b/countdown/countdown.d.ts @@ -3,11 +3,11 @@ // Definitions by: Gabriel Juchault // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'countdown' { - export type DateFunction = (timespan: Timespan) => void; - export type DateTime = number | Date | DateFunction; +declare namespace countdown { + type DateFunction = (timespan: Timespan) => void; + type DateTime = number | Date | DateFunction; - export interface Timespan { + interface Timespan { start?: Date; end?: Date; units?: number; @@ -26,7 +26,7 @@ declare module 'countdown' { toHTML(tagName?: string, label?: string): string; } - export interface Format { + interface Format { singular?: string | Array; plural?: string | Array; last?: string; @@ -36,7 +36,7 @@ declare module 'countdown' { formatter?(value: number, unit: number): string; } - export interface CountdownStatic { + interface CountdownStatic { (start: DateTime, end?: DateTime, units?: number, max?: number, digits?: number): Timespan | number; MILLENNIA: number; CENTURIES: number; @@ -64,6 +64,9 @@ declare module 'countdown' { resetFormat(): void; setFormat(format: Format): void; } +} - export let countdown: CountdownStatic; +declare module 'countdown' { + let countdown: countdown.CountdownStatic; + export = countdown; } From a6448a411a037ecfead7ba0f4d2eb24de8efce8b Mon Sep 17 00:00:00 2001 From: Gabriel JUCHAULT Date: Tue, 23 Aug 2016 13:27:40 +0200 Subject: [PATCH 106/844] Fix countdown types --- countdown/countdown-tests.ts | 10 +++++----- countdown/countdown.d.ts | 17 ++++++++++------- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/countdown/countdown-tests.ts b/countdown/countdown-tests.ts index c803f1acc2..3ad8890aab 100644 --- a/countdown/countdown-tests.ts +++ b/countdown/countdown-tests.ts @@ -1,15 +1,15 @@ /// -import { countdown, Timespan, CountdownStatic, Format } from 'countdown'; +import * as countdown from 'countdown'; -let ts: Timespan; +let ts: countdown.Timespan; let interval: number; -ts = countdown(new Date()); -ts = countdown(150); +ts = countdown(new Date()); +ts = countdown(150); interval = countdown(new Date(), - function (ts: Timespan) { + function (ts: countdown.Timespan) { document.getElementById('pageTimer').innerHTML = ts.toHTML('strong'); }, countdown.HOURS | countdown.MINUTES | countdown.SECONDS, diff --git a/countdown/countdown.d.ts b/countdown/countdown.d.ts index 5b40541dd0..bcb0d07976 100644 --- a/countdown/countdown.d.ts +++ b/countdown/countdown.d.ts @@ -3,11 +3,11 @@ // Definitions by: Gabriel Juchault // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'countdown' { - export type DateFunction = (timespan: Timespan) => void; - export type DateTime = number | Date | DateFunction; +declare namespace countdown { + type DateFunction = (timespan: Timespan) => void; + type DateTime = number | Date | DateFunction; - export interface Timespan { + interface Timespan { start?: Date; end?: Date; units?: number; @@ -26,7 +26,7 @@ declare module 'countdown' { toHTML(tagName?: string, label?: string): string; } - export interface Format { + interface Format { singular?: string | Array; plural?: string | Array; last?: string; @@ -36,7 +36,7 @@ declare module 'countdown' { formatter?(value: number, unit: number): string; } - export interface CountdownStatic { + interface CountdownStatic { (start: DateTime, end?: DateTime, units?: number, max?: number, digits?: number): Timespan | number; MILLENNIA: number; CENTURIES: number; @@ -64,6 +64,9 @@ declare module 'countdown' { resetFormat(): void; setFormat(format: Format): void; } +} - export let countdown: CountdownStatic; +declare module 'countdown' { + let countdown: countdown.CountdownStatic; + export = countdown; } From 69ecb66f736eb83b490c916f6be8ac65a5cf6163 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20S=C3=A1nchez?= Date: Mon, 22 Aug 2016 10:07:25 -0600 Subject: [PATCH 107/844] Made node Buffer's lastIndexOf and indexOf conformant to node API --- node/node-tests.ts | 11 +++++++++++ node/node.d.ts | 4 ++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index fd79f28f9d..bd19697f31 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -244,10 +244,21 @@ function bufferTests() { let index: number; index = buffer.indexOf("23"); index = buffer.indexOf("23", 1); + index = buffer.indexOf("23", 1, "utf8"); index = buffer.indexOf(23); index = buffer.indexOf(buffer); } + { + let buffer = new Buffer('123'); + let index: number; + index = buffer.lastIndexOf("23"); + index = buffer.lastIndexOf("23", 1); + index = buffer.lastIndexOf("23", 1, "utf8"); + index = buffer.lastIndexOf(23); + index = buffer.lastIndexOf(buffer); + } + // Imported Buffer from buffer module works properly { let b = new ImportedBuffer('123'); diff --git a/node/node.d.ts b/node/node.d.ts index 750d273988..d86dac906c 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -503,8 +503,8 @@ interface NodeBuffer extends Uint8Array { writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; fill(value: any, offset?: number, end?: number): this; - // TODO: encoding param - indexOf(value: string | number | Buffer, byteOffset?: number): number; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; // TODO: entries // TODO: includes // TODO: keys From c532a2d96c13392d92f70b8961dfa8cca159248d Mon Sep 17 00:00:00 2001 From: Zlatkovsky Date: Tue, 23 Aug 2016 12:13:16 -0700 Subject: [PATCH 108/844] Fixed "no implicit any" issue with previous commit. --- office-js/office-js.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/office-js/office-js.d.ts b/office-js/office-js.d.ts index 4f21022fe5..55b20f93cf 100644 --- a/office-js/office-js.d.ts +++ b/office-js/office-js.d.ts @@ -258,7 +258,7 @@ declare module OfficeExtension { /** * Creates a new promise based on a function that accepts resolve and reject handlers. */ - constructor(func: (resolve, reject) => void); + constructor(func: (resolve : (value?: R | IPromise) => void, reject: (error?: any) => void) => void); /** * Creates a promise that resolves when all of the child promises resolve. From 9e897a190c6a4dce539b0736771815c2bb7982a1 Mon Sep 17 00:00:00 2001 From: Simon Date: Tue, 23 Aug 2016 15:47:11 -0400 Subject: [PATCH 109/844] adds missing model() overrides --- mongoose-paginate/mongoose-paginate.d.ts | 6 ++++++ passport-local-mongoose/passport-local-mongoose.d.ts | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/mongoose-paginate/mongoose-paginate.d.ts b/mongoose-paginate/mongoose-paginate.d.ts index c90e7550fd..ed8b07a2fa 100644 --- a/mongoose-paginate/mongoose-paginate.d.ts +++ b/mongoose-paginate/mongoose-paginate.d.ts @@ -35,6 +35,12 @@ declare module 'mongoose' { schema?: Schema, collection?: string, skipInit?: boolean): PaginateModel; + + export function model>( + name: string, + schema?: Schema, + collection?: string, + skipInit?: boolean): U; } declare module 'mongoose-paginate' { diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts index acb834d85c..30319afc51 100644 --- a/passport-local-mongoose/passport-local-mongoose.d.ts +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -81,6 +81,12 @@ declare module 'mongoose' { schema?: PassportLocalSchema, collection?: string, skipInit?: boolean): PassportLocalModel; + + export function model>( + name: string, + schema?: PassportLocalSchema, + collection?: string, + skipInit?: boolean): U; } declare module 'passport-local-mongoose' { From 90d29903965a91b50866dfed61d8d164cf27a17f Mon Sep 17 00:00:00 2001 From: Simon Date: Tue, 23 Aug 2016 16:06:13 -0400 Subject: [PATCH 110/844] fixed connectionoption and .Mongoose travis errors --- mongoose/mongoose.d.ts | 9 +++++---- passport-local-mongoose/passport-local-mongoose.d.ts | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 50784a9194..89fc9073a4 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -93,6 +93,7 @@ declare module "mongoose" { export var DocumentProvider: any; // recursive constructor export var Mongoose: new(...args: any[]) => typeof mongoose; + type Mongoose = typeof mongoose; export var SchemaTypes: typeof Schema.Types; /** Expose connection states for user-land */ @@ -110,7 +111,7 @@ declare module "mongoose" { * @returns pseudo-promise wrapper around this */ export function connect(uris: string, - options?: ConnectOptions, + options?: ConnectionOptions, callback?: (err: mongodb.MongoError) => void): MongooseThenable; export function connect(uris: string, callback?: (err: mongodb.MongoError) => void): MongooseThenable; @@ -125,10 +126,10 @@ declare module "mongoose" { */ export function createConnection(): Connection; export function createConnection(uri: string, - options?: ConnectOptions + options?: ConnectionOptions ): Connection; export function createConnection(host: string, database_name: string, port?: number, - options?: ConnectOptions + options?: ConnectionOptions ): Connection; /** @@ -381,7 +382,7 @@ declare module "mongoose" { mongos?: boolean; } - interface ConnectOptions extends + interface ConnectionOptions extends ConnectionOpenOptions, ConnectionOpenSetOptions {} diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts index 30319afc51..2c189afc6a 100644 --- a/passport-local-mongoose/passport-local-mongoose.d.ts +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -16,7 +16,7 @@ declare module 'mongoose' { } // statics - interface PassportLocalModel extends Model { + interface PassportLocalModel extends Model { authenticate(): (username: string, password: string, cb: (err: any, res: T, error: any) => void) => void; serializeUser(): (user: PassportLocalModel, cb: (err: any) => void) => void; deserializeUser(): (username: string, cb: (err: any) => void) => void; From 76fc7cd3089c09deefe1a3e43b937cfd8b969d1b Mon Sep 17 00:00:00 2001 From: Michael Durling Date: Tue, 23 Aug 2016 16:08:06 -0400 Subject: [PATCH 111/844] Add allowHTML NotificationSystem property --- react-notification-system/react-notification-system.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/react-notification-system/react-notification-system.d.ts b/react-notification-system/react-notification-system.d.ts index 4f51314680..31b151662a 100644 --- a/react-notification-system/react-notification-system.d.ts +++ b/react-notification-system/react-notification-system.d.ts @@ -74,6 +74,7 @@ declare namespace NotificationSystem { noAnimation?: boolean; ref?: string; style?: Style | boolean; + allowHTML?: boolean; } } From 28b47d424e76cc0cfcb75d9299de97ee945da2d6 Mon Sep 17 00:00:00 2001 From: Simon Date: Tue, 23 Aug 2016 16:15:21 -0400 Subject: [PATCH 112/844] fixed travis errors for passport local mongoose and mongoose promise --- mongoose-promise/mongoose-promise-tests.ts | 2 +- passport-local-mongoose/passport-local-mongoose-tests.ts | 3 ++- passport-local-mongoose/passport-local-mongoose.d.ts | 4 ++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/mongoose-promise/mongoose-promise-tests.ts b/mongoose-promise/mongoose-promise-tests.ts index a7908c3db5..3970b2ac86 100644 --- a/mongoose-promise/mongoose-promise-tests.ts +++ b/mongoose-promise/mongoose-promise-tests.ts @@ -42,7 +42,7 @@ mongopromise.then(function (arg) { }); mongopromise.complete(); /* static properties */ -mongoose.Promise.ES6(function (complete, error) { +mongoose.Promise.ES6(function (complete: any, error: any) { complete.apply(this); error.apply(this); }); diff --git a/passport-local-mongoose/passport-local-mongoose-tests.ts b/passport-local-mongoose/passport-local-mongoose-tests.ts index c7d4ffc381..dcdf08bbe3 100644 --- a/passport-local-mongoose/passport-local-mongoose-tests.ts +++ b/passport-local-mongoose/passport-local-mongoose-tests.ts @@ -11,6 +11,7 @@ import { Schema, model, + Document, PassportLocalDocument, PassportLocalSchema, PassportLocalModel, @@ -77,7 +78,7 @@ options.errorMessages = errorMessages; UserSchema.plugin(passportLocalMongoose, options); -interface UserModel extends PassportLocalModel {} +interface UserModel extends PassportLocalModel {} let UserModel: UserModel = model('User', UserSchema); //#endregion diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts index 2c189afc6a..ab2539a709 100644 --- a/passport-local-mongoose/passport-local-mongoose.d.ts +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -76,13 +76,13 @@ declare module 'mongoose' { ): this; } - export function model( + export function model( name: string, schema?: PassportLocalSchema, collection?: string, skipInit?: boolean): PassportLocalModel; - export function model>( + export function model>( name: string, schema?: PassportLocalSchema, collection?: string, From aefccb9b431554179eaddf90281ac0b73a701a33 Mon Sep 17 00:00:00 2001 From: Michael Durling Date: Tue, 23 Aug 2016 16:23:34 -0400 Subject: [PATCH 113/844] Fix name of Pusher interface property - sessionId is incorrect, should be sessionID --- pusher-js/pusher-js.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pusher-js/pusher-js.d.ts b/pusher-js/pusher-js.d.ts index 0a6dc18d24..76bdb83c0e 100644 --- a/pusher-js/pusher-js.d.ts +++ b/pusher-js/pusher-js.d.ts @@ -23,7 +23,7 @@ declare module "pusher-js" { config: Config; //TODO: add GlobalConfig typings channels: any; //TODO: Type this global_emitter: EventsDispatcher; - sessionId: number; + sessionID: number; timeline: any; //TODO: Type this connection: ConnectionManager; } From e729485568cee259f220eea8c4f8a8536c3a78c7 Mon Sep 17 00:00:00 2001 From: grippstick Date: Tue, 23 Aug 2016 16:55:34 -0500 Subject: [PATCH 114/844] added the enum used in requestFileSystem --- cordova/plugins/FileSystem.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cordova/plugins/FileSystem.d.ts b/cordova/plugins/FileSystem.d.ts index 66a6014dea..f9471eda72 100644 --- a/cordova/plugins/FileSystem.d.ts +++ b/cordova/plugins/FileSystem.d.ts @@ -15,7 +15,7 @@ interface Window { * @param errorCallback A callback that is called when errors happen, or when the request to obtain the filesystem is denied. */ requestFileSystem( - type: number, + type: LocalFileSystem, size: number, successCallback: (fileSystem: FileSystem) => void, errorCallback?: (fileError: FileError) => void): void; @@ -371,3 +371,8 @@ interface Cordova { } } + +declare enum LocalFileSystem { + PERSISTENT=0, + TEMPORARY=1 +} From d0d8127eaa52ec102d65ba7c217ae948d275f8aa Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Fri, 22 Jul 2016 17:32:00 +0300 Subject: [PATCH 115/844] Fix withWidth return type signature to be a HOC `withWidth` is a function that returns a high order component wrapper function. More info here: https://github.com/callemall/material-ui/blob/master/src/utils/withWidth.js#L15 --- material-ui/material-ui-tests.tsx | 4 ++++ material-ui/material-ui.d.ts | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/material-ui/material-ui-tests.tsx b/material-ui/material-ui-tests.tsx index c47f82858b..d350025217 100644 --- a/material-ui/material-ui-tests.tsx +++ b/material-ui/material-ui-tests.tsx @@ -112,6 +112,8 @@ import {cyan500, cyan700, } from 'material-ui/styles/colors'; import {fade} from 'material-ui/utils/colorManipulator'; +import {SMALL, MEDIUM, LARGE, default as withWidth} from 'material-ui/utils/withWidth'; + import injectTapEventPlugin = require('react-tap-event-plugin'); @@ -4926,6 +4928,8 @@ class ToolbarExamplesSimple extends React.Component<{}, {value?: number}> { } } +const componentWithWidth = withWidth()(ToolbarExamplesSimple); + interface MaterialUiTestsState { } diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index 6d48b46e58..2913c0bd57 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -7228,7 +7228,7 @@ declare module 'material-ui/utils/withWidth' { mediumWidth?: number; resizeInterval?: number; } - export default function withWidth(options?: Options): __React.ComponentClass + export default function withWidth(options?: Options): (component: C) => C; } declare namespace __MaterialUI.Styles { From 9c5f574dd8d8b2a385cdff6e260123ec8e78ad40 Mon Sep 17 00:00:00 2001 From: Erwin Poeze Date: Wed, 24 Aug 2016 16:26:52 +0200 Subject: [PATCH 116/844] Removed generic type from Reduced --- ramda/ramda.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ramda/ramda.d.ts b/ramda/ramda.d.ts index a6fa682a3a..04623bdada 100644 --- a/ramda/ramda.d.ts +++ b/ramda/ramda.d.ts @@ -107,7 +107,7 @@ declare namespace R { (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6): R; } - interface Reduced {} + interface Reduced {} interface Static { @@ -1300,9 +1300,9 @@ declare namespace R { * function and passing it an accumulator value and the current value from the array, and * then passing the result to the next call. */ - reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult, list: T[]): TResult; - reduce(fn: (acc: TResult, elem: T) => TResult|Reduced): (acc: TResult, list: T[]) => TResult; - reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult): (list: T[]) => TResult; + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult, list: T[]): TResult; + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced): (acc: TResult, list: T[]) => TResult; + reduce(fn: (acc: TResult, elem: T) => TResult|Reduced, acc: TResult): (list: T[]) => TResult; /** * Groups the elements of the list according to the result of calling the String-returning function keyFn on each @@ -1318,7 +1318,7 @@ declare namespace R { * transduce functions. The returned value should be considered a black box: the internal * structure is not guaranteed to be stable. */ - reduced(elem: T): Reduced; + reduced(elem: T): Reduced; /** * Returns a single item by iterating through the list, successively calling the iterator From 2ebcbf744729d1e4b305454cfdfbe3abdafb066a Mon Sep 17 00:00:00 2001 From: Hristian Hristov Date: Wed, 24 Aug 2016 16:13:49 +0100 Subject: [PATCH 117/844] Add module 'process' --- node/node.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/node/node.d.ts b/node/node.d.ts index d86dac906c..280f17e045 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2625,3 +2625,8 @@ declare module "constants" { export var X_OK: number; export var UV_UDP_REUSEADDR: number; } + +declare module "process" { + var p: NodeJS.Process; + export default p; +} \ No newline at end of file From a94bce4fff73a65b3a4471b6ce91780cc09ece5c Mon Sep 17 00:00:00 2001 From: ltrain777 Date: Wed, 24 Aug 2016 09:05:30 -0700 Subject: [PATCH 118/844] Fix json method signatures to match restler apis to pass json data. (#10736) --- restler/restler-tests.ts | 18 ++++++++++++++++-- restler/restler.d.ts | 12 ++++++++---- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/restler/restler-tests.ts b/restler/restler-tests.ts index a709fc3375..8c53455d08 100644 --- a/restler/restler-tests.ts +++ b/restler/restler-tests.ts @@ -33,14 +33,28 @@ rest.post("http://user:pass@service.com/action", { } }); -// post JSON +// post JSON with no options var jsonData = { id: 334 }; rest.postJson("http://example.com/action", jsonData).on("complete", function(data, response) { // handle response }); -// put JSON +// put JSON with no options var jsonData = { id: 334 }; rest.putJson("http://example.com/action", jsonData).on("complete", function(data, response) { // handle response }); + +// post JSON with options +var jsonData = { id: 334 }; +var options = { query: {"api-version": "1.0"}}; +rest.postJson("http://example.com/action", jsonData, options).on("complete", function(data, response) { + // handle response +}); + +// put JSON with options +var jsonData = { id: 334 }; +var options = { query: {"api-version": "1.0"}}; +rest.putJson("http://example.com/action", jsonData, options).on("complete", function(data, response) { + // handle response +}); diff --git a/restler/restler.d.ts b/restler/restler.d.ts index b504a4e75d..389203066d 100644 --- a/restler/restler.d.ts +++ b/restler/restler.d.ts @@ -40,10 +40,11 @@ declare module "restler" { /** * Send json data via GET method. * @param {string} url A url address. + * @param {any} data JSON body * @param {RestlerOptions} options Options. * @return {RestlerResult} Result. */ - json(url: string, options?: RestlerOptions): RestlerResult; + json(url: string, data?: any, options?: RestlerOptions, method?: string): RestlerResult; /** * Create a PATCH request. @@ -56,10 +57,11 @@ declare module "restler" { /** * Send json data via PATCH method. * @param {string} url A url address. + * @param {any} data JSON body * @param {RestlerOptions} options Options. * @return {RestlerResult} Result. */ - patchJson(url: string, options?: RestlerOptions): RestlerResult; + patchJson(url: string, data?: any, options?: RestlerOptions): RestlerResult; /** * Create a POST request. @@ -72,10 +74,11 @@ declare module "restler" { /** * Send json data via POST method. * @param {string} url A url address. + * @param {any} data JSON body * @param {RestlerOptions} options Options. * @return {RestlerResult} Result. */ - postJson(url: string, options?: RestlerOptions): RestlerResult; + postJson(url: string, data?: any, options?: RestlerOptions): RestlerResult; /** * Create a PUT request. @@ -88,10 +91,11 @@ declare module "restler" { /** * Send json data via PUT method. * @param {string} url A url address. + * @param {any} data JSON body * @param {RestlerOptions} options Options. * @return {RestlerResult} Result. */ - putJson(url: string, options?: RestlerOptions): RestlerResult; + putJson(url: string, data?: any, options?: RestlerOptions): RestlerResult; /** * Create a PUT request. From aba1694d0c591ff49e81115a46e2479d89a9ea84 Mon Sep 17 00:00:00 2001 From: Jack Moore Date: Wed, 24 Aug 2016 11:06:06 -0500 Subject: [PATCH 119/844] New definition for universal-router (#10744) * New definition for universal-router * Changed undefined return type to void --- universal-router/universal-router-tests.ts | 99 ++++++++++++++++++++++ universal-router/universal-router.d.ts | 70 +++++++++++++++ 2 files changed, 169 insertions(+) create mode 100644 universal-router/universal-router-tests.ts create mode 100644 universal-router/universal-router.d.ts diff --git a/universal-router/universal-router-tests.ts b/universal-router/universal-router-tests.ts new file mode 100644 index 0000000000..922ca137ad --- /dev/null +++ b/universal-router/universal-router-tests.ts @@ -0,0 +1,99 @@ +/// + +import {ActionContext, Params, resolve } from "universal-router"; + +// Test 1 +const routes1 = [ + { + path: "/one", + action: () => "Page One" + }, + { + path: "/two", + action: () => "Page Two" + } +]; + +resolve(routes1, { path: "/one" }) + .then(result => console.log(result)); + +// Test 2 +const routes2 = [ + { + path: "/hello/:username", + action: (context: ActionContext) => `Welcome, ${context.params["username"]}!` + } +]; + +resolve(routes2, { path: "/hello/john" }) + .then(result => console.log(result)); + + +// Test 3 +const routes3 = [ + { + path: "/hello/:username", + action: (ctx: ActionContext, { username }: Params) => `Welcome, ${username}!` + } +]; + +resolve(routes3, { path: "/hello/john" }) + .then(result => console.log(result)); + + +// Test 4 +const routes4 = [ + { + path: "/hello", + action: () => new Promise(resolve => { + setTimeout(() => resolve("Welcome!"), 1000); + }) + } +]; + +resolve(routes4, { path: "/hello" }) + .then(result => console.log(result)); + +// Test 5 +const routes5 = [ + { + path: "/hello/:username", + async action(ctx: ActionContext, { username }: Params) { + const waitable = async (name: string) => { + console.log(`Welcome ${name}`); + } + await waitable(username); + } + } +]; + +resolve(routes5, { path: "/hello/john" }) + .then(result => console.log(result)); + +// Test 6 +const routes6 = [ + { path: "/one", action: () => "

    Page One

    " }, + { path: "/two", action: () => "

    Page Two

    " } +]; + +resolve(routes6, { path: "/one" }).then(result => { + document.body.innerHTML = result || "

    Not Found

    "; +}); + +// Test 7 +interface Render { + render: typeof render; +} + +const routes7 = [ + { path: "/one", action: ({ render: func }: ActionContext & Render) => func("

    Page One

    ") }, + { path: "/two", action: ({ render: func }: ActionContext & Render) => func("

    Page Two

    ") } +]; + +function render(component: string) { + return new Promise(resolve => { + console.log(`Rendering... ${component}`); + }); +} + +resolve>(routes7, { path: "/one", render }); diff --git a/universal-router/universal-router.d.ts b/universal-router/universal-router.d.ts new file mode 100644 index 0000000000..6acba5c179 --- /dev/null +++ b/universal-router/universal-router.d.ts @@ -0,0 +1,70 @@ +// Type definitions for universal-router +// Project: https://github.com/kriasoft/universal-router +// Definitions by: Jack Moore +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "universal-router" { + /** + * Params is a key/value object that represents extracted URL paramters. Each + * URL parameter resolves to a string. + */ + export interface Params { + [key: string]: string; + } + + /** + * Context represents the context that is passed as the second argument + * passed to resolve. By default, it only is require to contain a path, but + * can be extended by the way of generics. + */ + export interface Context { + path: string; + } + + /** + * ActionContext is similar to Context, with the exception of an added params + * object. ActionContext is passed as the first argument to the action + * function. + */ + export interface ActionContext extends Context { + params: Params; + } + + /** + * A Route is a singular route in your application. It contains a path, an + * action function, and optional children which are an array of Route. + * + * @template C User context that is made union with ActionContext. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + */ + export interface Route { + path: string; + action: (ctx: ActionContext & C, params: Params) => R | Promise | void; + children?: Routes; + } + + /** + * Routes in an array of type Route. + * @template C User context that is made union with ActionContext. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + */ + export type Routes = Route[]; + + /** + * Resolve function that is given routes and a path or context object. + * Returns a Promise that resolves to result of the action function of the + * matched route. + * + * @template C User context that is made union with Context. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + * + * @param {Routes | Route} routes - Single route or array of routes. + * @param {string | String | Context & C} pathOrContext - path to resolve or + * context object that contains the path along with other data. + * @return {Promise} - Result of matched action function wrapped in a Promsie. + */ + export function resolve(routes: Routes | Route, pathOrContext: string | String | Context & C): Promise +} \ No newline at end of file From 1fa21ec5019826429cf99b8b87175f9ec59407e0 Mon Sep 17 00:00:00 2001 From: "Keith D. Moore" Date: Wed, 24 Aug 2016 11:07:10 -0500 Subject: [PATCH 120/844] add typings for pouchdb-upsert. resolves #10596 (#10752) --- pouchdb-upsert/pouchdb-upsert-tests.ts | 49 +++++++++++++++++++ pouchdb-upsert/pouchdb-upsert.d.ts | 66 ++++++++++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100644 pouchdb-upsert/pouchdb-upsert-tests.ts create mode 100644 pouchdb-upsert/pouchdb-upsert.d.ts diff --git a/pouchdb-upsert/pouchdb-upsert-tests.ts b/pouchdb-upsert/pouchdb-upsert-tests.ts new file mode 100644 index 0000000000..fa4eb83af3 --- /dev/null +++ b/pouchdb-upsert/pouchdb-upsert-tests.ts @@ -0,0 +1,49 @@ +/// + +import * as pouchdbUpsert from 'pouchdb-upsert'; +PouchDB.plugin(pouchdbUpsert); + +namespace PouchDBUpsertTests { + type UpsertDocModel = { _id: 'test-doc1', name: 'test' }; + let docToUpsert: PouchDB.Core.Document; + const db = new PouchDB(); + + function testUpsert_WithPromise_AndReturnDoc() { + db.upsert(docToUpsert._id, (doc: PouchDB.Core.Document) => { + // Make some updates.... + return doc; + }).then((res: PouchDB.Core.Response) => { + }); + } + + function testUpsert_WithPromise_AndReturnBoolean() { + db.upsert(docToUpsert._id, (doc: PouchDB.Core.Document) => { + // Make some updates.... + return false; + }).then((res: PouchDB.Core.Response) => { + }); + } + + function testUpsert_WithCallback_AndReturnDoc() { + db.upsert(docToUpsert._id, (doc: PouchDB.Core.Document) => { + // Make some updates.... + return doc; + }, (res: PouchDB.Core.Response) => {}); + } + + function testUpsert_WithCallback_AndReturnBoolean() { + // callback return boolean + db.upsert(docToUpsert._id, (doc: PouchDB.Core.Document) => { + // Make some updates.... + return false; + }, (res: PouchDB.Core.Response) => {}); + } + + function testPutIfNotExists_WithPromise() { + db.putIfNotExists(docToUpsert).then( (res: PouchDB.Core.Response) => {}); + } + + function testPutIfNotExists_WithCallback() { + db.putIfNotExists(docToUpsert, (res: PouchDB.Core.Response) => {}); + } +} diff --git a/pouchdb-upsert/pouchdb-upsert.d.ts b/pouchdb-upsert/pouchdb-upsert.d.ts new file mode 100644 index 0000000000..b0a4e760a3 --- /dev/null +++ b/pouchdb-upsert/pouchdb-upsert.d.ts @@ -0,0 +1,66 @@ +// Type definitions for pouchdb-upsert v2.0.1 +// Project: https://github.com/pouchdb/upsert +// Definitions by: Keith D. Moore , Andrew Mitchell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace PouchDB { + + interface Database { + /** + * Perform an upsert (update or insert) operation. Returns a Promise. + * + * @param docId - the _id of the document. + * @param diffFun - function that takes the existing doc as input and returns an updated doc. + * If this diffFunc returns falsey, then the update won't be performed (as an optimization). + * If the document does not already exist, then {} will be the input to diffFunc. + * + */ + upsert(docId: Core.DocumentId, diffFun: UpsertDiffCallback): Promise; + + /** + * Perform an upsert (update or insert) operation. If a callback is not provided, the Promise based version + * of this function will be called. + * + * @param docId - the _id of the document. + * @param diffFun - function that takes the existing doc as input and returns an updated doc. + * If this diffFunc returns falsey, then the update won't be performed (as an optimization). + * If the document does not already exist, then {} will be the input to diffFunc. + * @param callback - called with the results after operation is completed. + */ + upsert(docId: Core.DocumentId, diffFun: UpsertDiffCallback, + callback: Core.Callback): void; + + /** + * Put a new document with the given docId, if it doesn't already exist. Returns a Promise. + * + * @param doc - the document to insert. Should contain an _id if docId is not specified + * If the document already exists, then the Promise will just resolve immediately. + */ + putIfNotExists(doc: Core.Document): Promise; + + // + /** + * Put a new document with the given docId, if it doesn't already exist. If a callback is not provided, + * the Promise based version of this function will be called. + * + * @param doc - the document to insert. Should contain an _id if docId is not specified + * If the document already exists, then the Promise will just resolve immediately. + * @param callback - called with the results after operation is completed. + * If you don't specify a callback, then the Promise version of this function will be invoked and it + * will return a Promise. + */ + putIfNotExists(doc: Core.Document, + callback: Core.Callback): void; + } + + interface UpsertDiffCallback { + (doc: Core.Document): Core.Document|boolean; + } +} + +declare module 'pouchdb-upsert' { + const plugin: PouchDB.Plugin; + export = plugin; +} From 77bc119042bdf92f5740d912a3a3bb336437ac08 Mon Sep 17 00:00:00 2001 From: Steven Date: Wed, 24 Aug 2016 09:11:07 -0700 Subject: [PATCH 121/844] Add extra static members to the Node v4 Error class (#10747) Defines `stackTraceLimit` and `captureStackTrace` as static members for the Error class in Node v4 so their usage can be recognized. --- node/node-4-tests.ts | 14 ++++++++++++++ node/node-4.d.ts | 4 ++++ 2 files changed, 18 insertions(+) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 8cddf66987..9db708b910 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -826,3 +826,17 @@ namespace vm_tests { Debug.scripts().forEach(function(script: any) { console.log(script.name); }); } } + +/////////////////////////////////////////////////////////////////////////////// +/// Errors Tests : https://nodejs.org/dist/latest-v4.x/docs/api/errors.html /// +/////////////////////////////////////////////////////////////////////////////// + +namespace errors_tests { + { + Error.stackTraceLimit = Infinity; + } + { + const myObject = {}; + Error.captureStackTrace(myObject); + } +} \ No newline at end of file diff --git a/node/node-4.d.ts b/node/node-4.d.ts index e60da8e309..848b0536d0 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -13,6 +13,10 @@ interface Error { stack?: string; } +interface ErrorConstructor { + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + stackTraceLimit: number; +} // compat for TypeScript 1.8 // if you use with --target es3 or --target es5 and use below definitions, From d7c91b7a92d4e42ca50d375454b869e06bb80bb3 Mon Sep 17 00:00:00 2001 From: "Keith D. Moore" Date: Wed, 24 Aug 2016 11:28:27 -0500 Subject: [PATCH 122/844] add remove function typings to pouchdb-core (#10754) --- pouchdb-core/pouchdb-core-tests.ts | 27 +++++++++++++++++++++++++++ pouchdb-core/pouchdb-core.d.ts | 14 ++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/pouchdb-core/pouchdb-core-tests.ts b/pouchdb-core/pouchdb-core-tests.ts index ac7a6c3e69..71f5db7d63 100644 --- a/pouchdb-core/pouchdb-core-tests.ts +++ b/pouchdb-core/pouchdb-core-tests.ts @@ -75,4 +75,31 @@ namespace PouchDBCoreTests { db.info({ ajax: { cache: true }}, (error, result) => { }); } + + function testRemove() { + type MyModel = { rev: 'rev', property: 'someProperty '}; + let model: PouchDB.Core.Document; + const id = 'model'; + const rev = 'rev'; + + const db = new PouchDB(); + + // Promise version with doc + db.remove(model).then( (res: PouchDB.Core.Response) => {}); + + // Promise version with doc and options + db.remove(model, {}).then( (res: PouchDB.Core.Response) => {}); + + // Promise version with docId and rev + db.remove(id, rev).then( (res: PouchDB.Core.Response) => {}); + + // Promise version with docId and rev and options + db.remove(id, rev, {}).then( (res: PouchDB.Core.Response) => {}); + + // Callback version with doc + db.remove(model, {}, (res: PouchDB.Core.Response) => {}); + + // Callback version with docId and rev + db.remove(id, rev, {}, (res: PouchDB.Core.Response) => {}); + } } diff --git a/pouchdb-core/pouchdb-core.d.ts b/pouchdb-core/pouchdb-core.d.ts index a8b6418510..1a56e51785 100644 --- a/pouchdb-core/pouchdb-core.d.ts +++ b/pouchdb-core/pouchdb-core.d.ts @@ -319,6 +319,20 @@ declare namespace PouchDB { revision?: Core.RevisionId, options?: Core.PutOptions): Promise; + /** Remove a doc from the database */ + remove(doc: Core.Document, + options: Core.Options, + callback: Core.Callback): void; + remove(docId: Core.DocumentId, + revision: Core.RevisionId, + options: Core.Options, + callback: Core.Callback): void; + remove(doc: Core.Document, + options?: Core.Options): Promise; + remove(docId: Core.DocumentId, + revision: Core.RevisionId, + options?: Core.Options): Promise; + /** Get database information */ info(options: Core.InfoOptions | void, callback: Core.Callback): void; From 3f9b9ed351d9fc5c64576de74527ba923f5d6ed0 Mon Sep 17 00:00:00 2001 From: "Keith D. Moore" Date: Wed, 24 Aug 2016 11:28:54 -0500 Subject: [PATCH 123/844] add compact function typings to pouchdb-core (#10753) --- pouchdb-core/pouchdb-core-tests.ts | 10 ++++++++++ pouchdb-core/pouchdb-core.d.ts | 9 +++++++++ 2 files changed, 19 insertions(+) diff --git a/pouchdb-core/pouchdb-core-tests.ts b/pouchdb-core/pouchdb-core-tests.ts index 71f5db7d63..b46bce834d 100644 --- a/pouchdb-core/pouchdb-core-tests.ts +++ b/pouchdb-core/pouchdb-core-tests.ts @@ -38,6 +38,16 @@ namespace PouchDBCoreTests { }); } + function testCompact() { + const db = new PouchDB<{}>(); + // Promise version + db.compact().then( (res: PouchDB.Core.Response) => {}); + // Promise version with optional options + db.compact({interval: 300}).then( (res: PouchDB.Core.Response) => {}); + // Options with a callback + db.compact({interval: 300}, (res: PouchDB.Core.Response) => {}); + } + function testDestroy() { const db = new PouchDB<{}>(); diff --git a/pouchdb-core/pouchdb-core.d.ts b/pouchdb-core/pouchdb-core.d.ts index 1a56e51785..b0498e76af 100644 --- a/pouchdb-core/pouchdb-core.d.ts +++ b/pouchdb-core/pouchdb-core.d.ts @@ -164,6 +164,10 @@ declare namespace PouchDB { interface PostOptions extends PutOptions { } + interface CompactOptions extends Core.Options { + interval?: number; + } + interface InfoOptions extends Options { } } @@ -264,6 +268,11 @@ declare namespace PouchDB { allDocs(options?: Core.AllDocsOptions): Promise>; + /** Compact the database */ + compact(options?: Core.CompactOptions): Promise; + compact(options: Core.CompactOptions, + callback: Core.Callback): void; + /** Destroy the database */ destroy(options: Core.DestroyOptions | void, callback: Core.AnyCallback): void; From ccf79bc4f71390d180da5ef4499f61fed1f69077 Mon Sep 17 00:00:00 2001 From: nickp10 Date: Wed, 24 Aug 2016 10:31:03 -0600 Subject: [PATCH 124/844] Adding definitions for the set-cookie-parser library (#10756) * Adding definitions for the set-cookie-parser library * Adding newline to end of file --- set-cookie-parser/set-cookie-parser-tests.ts | 45 ++++++++++++++++++++ set-cookie-parser/set-cookie-parser.d.ts | 27 ++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 set-cookie-parser/set-cookie-parser-tests.ts create mode 100644 set-cookie-parser/set-cookie-parser.d.ts diff --git a/set-cookie-parser/set-cookie-parser-tests.ts b/set-cookie-parser/set-cookie-parser-tests.ts new file mode 100644 index 0000000000..731d38efaa --- /dev/null +++ b/set-cookie-parser/set-cookie-parser-tests.ts @@ -0,0 +1,45 @@ +/// +/// + +import assert = require("assert"); +import http = require("http"); +import setCookie = require("set-cookie-parser"); + +// Required properties only test +var requiredOnly = "foo=bar;"; +var cookies = setCookie(requiredOnly); +assert.equal(cookies.length, 1); +assert.equal(cookies[0].name, "foo"); +assert.equal(cookies[0].value, "bar"); + +// Optional properties included test +var optionalIncluded = "foo=bar; Max-Age=1000; Domain=.example.com; Path=/; Expires=Tue, 01 Jul 2025 10:01:11 GMT; HttpOnly; Secure"; +cookies = setCookie(optionalIncluded); +assert.equal(cookies.length, 1); +assert.equal(cookies[0].name, "foo"); +assert.equal(cookies[0].value, "bar"); +assert.equal(cookies[0].domain, ".example.com"); +assert.equal(cookies[0].path, "/"); +assert.deepEqual(cookies[0].expires, new Date('Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)')); +assert.equal(cookies[0].maxAge, 1000); +assert.equal(cookies[0].httpOnly, true); +assert.equal(cookies[0].secure, true); + +// Array of strings test +var arrayOfCookies = ["bam=baz", "foo=bar"]; +cookies = setCookie(arrayOfCookies); +assert.equal(cookies.length, 2); +assert.equal(cookies[0].name, "bam"); +assert.equal(cookies[0].value, "baz"); +assert.equal(cookies[1].name, "foo"); +assert.equal(cookies[1].value, "bar"); + +// HTTP response message test +var message = {}; +message.headers = { "set-cookie": ["bam=baz", "foo=bar"] }; +cookies = setCookie(message); +assert.equal(cookies.length, 2); +assert.equal(cookies[0].name, "bam"); +assert.equal(cookies[0].value, "baz"); +assert.equal(cookies[1].name, "foo"); +assert.equal(cookies[1].value, "bar"); diff --git a/set-cookie-parser/set-cookie-parser.d.ts b/set-cookie-parser/set-cookie-parser.d.ts new file mode 100644 index 0000000000..91ca3ef2c1 --- /dev/null +++ b/set-cookie-parser/set-cookie-parser.d.ts @@ -0,0 +1,27 @@ +// Type definitions for set-cookie-parser +// Project: https://github.com/nfriedly/set-cookie-parser +// Definitions by: Nick Paddock +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "set-cookie-parser" { + import http = require("http"); + + function SetCookieParser(input: string | string[] | http.IncomingMessage): SetCookieParser.Cookie[]; + + namespace SetCookieParser { + interface Cookie { + name: string; + value: string; + path?: string; + expires?: Date; + maxAge?: number; + domain?: string; + secure?: boolean; + httpOnly?: boolean; + } + } + + export = SetCookieParser; +} From f0fede9ce3fb165fe254c367e44a2370fa033735 Mon Sep 17 00:00:00 2001 From: Giacomo Rebonato Date: Wed, 24 Aug 2016 17:33:31 +0100 Subject: [PATCH 125/844] added minSize and maxSide to React-Dropzone (#10755) * added minSize and maxSide * added comment to properties and fixed test --- react-dropzone/react-dropzone-tests.tsx | 2 ++ react-dropzone/react-dropzone.d.ts | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/react-dropzone/react-dropzone-tests.tsx b/react-dropzone/react-dropzone-tests.tsx index 6216b5f20e..ca3d462596 100644 --- a/react-dropzone/react-dropzone-tests.tsx +++ b/react-dropzone/react-dropzone-tests.tsx @@ -19,6 +19,8 @@ class Test extends React.Component { style={{ borderStyle: "dashed" }} activeStyle={{ borderStyle: "dotted" }} className="regular" + minSize={2000} + maxSize={Infinity} activeClassName="active" rejectClassName="reject" disableClick={true} diff --git a/react-dropzone/react-dropzone.d.ts b/react-dropzone/react-dropzone.d.ts index a8198524de..792fd436ba 100644 --- a/react-dropzone/react-dropzone.d.ts +++ b/react-dropzone/react-dropzone.d.ts @@ -22,6 +22,14 @@ declare namespace ReactDropzone { * Clicking the brings up the browser file picker. To disable, set to true. */ disableClick?: boolean; + /** + * Min file size accepted + */ + minSize?: number; + /** + * Max file size accepted + */ + maxSize?: number; /** * To accept only a single file, set this to false. */ From 882c5665a1031acb2a791af1928b3b26a129e094 Mon Sep 17 00:00:00 2001 From: York Yao Date: Thu, 25 Aug 2016 00:38:18 +0800 Subject: [PATCH 126/844] add type of socket.io-parser (#10761) * add type of socket.io-parser * fix CI --- socket.io-parser/socket.io-parser-tests.ts | 41 ++++++++++++++++++++++ socket.io-parser/socket.io-parser.d.ts | 39 ++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 socket.io-parser/socket.io-parser-tests.ts create mode 100644 socket.io-parser/socket.io-parser.d.ts diff --git a/socket.io-parser/socket.io-parser-tests.ts b/socket.io-parser/socket.io-parser-tests.ts new file mode 100644 index 0000000000..917f72500f --- /dev/null +++ b/socket.io-parser/socket.io-parser-tests.ts @@ -0,0 +1,41 @@ +/// +/// + +import * as parser from 'socket.io-parser'; +var encoder = new parser.Encoder(); +var packet = { + type: parser.EVENT, + data: 'test-packet', + id: 13 +}; +encoder.encode(packet, function (encodedPackets) { + var decoder = new parser.Decoder(); + decoder.on('decoded', function (decodedPacket) { + decodedPacket.type == parser.EVENT + decodedPacket.data == 'test-packet' + decodedPacket.id == 13 + }); + + for (var i = 0; i < encodedPackets.length; i++) { + decoder.add(encodedPackets[i]); + } +}); + +var packet2 = { + type: parser.BINARY_EVENT, + data: { i: new Buffer(1234), j: new Blob([new ArrayBuffer(2)]) }, + id: 15 +}; +encoder.encode(packet2, function (encodedPackets) { + var decoder = new parser.Decoder(); + decoder.on('decoded', function (decodedPacket) { + decodedPacket.type == parser.BINARY_EVENT + Buffer.isBuffer(decodedPacket.data.i) == true + Buffer.isBuffer(decodedPacket.data.j) == true + decodedPacket.id == 15 + }); + + for (var i = 0; i < encodedPackets.length; i++) { + decoder.add(encodedPackets[i]); + } +}); diff --git a/socket.io-parser/socket.io-parser.d.ts b/socket.io-parser/socket.io-parser.d.ts new file mode 100644 index 0000000000..0c4903fda4 --- /dev/null +++ b/socket.io-parser/socket.io-parser.d.ts @@ -0,0 +1,39 @@ +// Type definitions for json-editor +// Project: https://github.com/socketio/socket.io-parser +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "socket.io-parser" { + namespace Parser { + type Packet = { + type: number, + data: any, + id: number + } + type EncodedPacket = string | Buffer | ArrayBuffer | Blob; + + var types: string[]; + + var CONNECT: number; + var DISCONNECT: number; + var EVENT: number; + var ACK: number; + var ERROR: number; + var BINARY_EVENT: number; + var BINARY_ACK: number; + + class Encoder { + encode(packet: Packet, callback: (encodedPackets: EncodedPacket[]) => void): void; + } + + class Decoder { + on(event: string, callback: (decodedPacket: Packet) => void): void; + add(encodedPacket: EncodedPacket): void; + destroy(): void; + } + } + + export = Parser; +} From 23c9f2230960c4a9b83e4297471d082a27d02b74 Mon Sep 17 00:00:00 2001 From: David Herges Date: Wed, 24 Aug 2016 18:38:38 +0200 Subject: [PATCH 127/844] Adding type definitions for 'halfred' (#10764) --- halfred/halfred-tests.ts | 13 +++ halfred/halfred.d.ts | 247 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 260 insertions(+) create mode 100644 halfred/halfred-tests.ts create mode 100644 halfred/halfred.d.ts diff --git a/halfred/halfred-tests.ts b/halfred/halfred-tests.ts new file mode 100644 index 0000000000..3aecf39962 --- /dev/null +++ b/halfred/halfred-tests.ts @@ -0,0 +1,13 @@ +/// + +// run test with: $ tsc --noImplicitAny --target es6 --module commonjs halfred-tests.ts +import { parse } from 'halfred'; // require('halfred'); +let resource = parse({foo: "bar", "_links": { "self": { href: "fooo" }}}); +console.log(resource); + +let allLinks = resource.allLinks(); +for (let key in allLinks) { + let link = allLinks[key]; + + console.log(link[0].href); +} diff --git a/halfred/halfred.d.ts b/halfred/halfred.d.ts new file mode 100644 index 0000000000..9c1d571a9d --- /dev/null +++ b/halfred/halfred.d.ts @@ -0,0 +1,247 @@ +// Type definitions for Halfred v1.0.0 +// Project: https://github.com/basti1302/halfred +// Definitions by: David Herges +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module "halfred" { + + /** + * halfred.parse(object) returns a Resource object. + * + * @see https://github.com/basti1302/halfred#usage + */ + export function parse(object: any): Resource; + + /** @see https://github.com/basti1302/halfred#enabledisable-validation */ + export function enableValidation(flag: boolean): void; + + /** @see https://github.com/basti1302/halfred#enabledisable-validation */ + export function disableValidation(): void; + + /** @see https://github.com/basti1302/halfred#resource-api */ + export interface Resource { + + /** + * Returns an object which has an array for each link that was present in the source object. + * See below why each link is represented as an array. + */ + allLinkArrays(): LinkCollection; + + /** Alias for allLinkArrays() */ + allLinks(): LinkCollection; + + /** + * Returns the array of links for the given key, or null if there are no links for this key. + */ + linkArray(key: string): Link[]; + + /** + * Returns the first element of the array of links for the given key or null if there are no + * links for this key. + */ + link(key: string): Link; + + /** + * Returns an object which has an array for each embedded resource that was present in the + * source object. + * See below why each embedded resource is represented as an array. Each element of any of + * this arrays is in turn a Resource object. + */ + allEmbeddedResourceArrays(): ResourceCollection; + + /** Alias for allEmbeddedResourceArrays() */ + allEmbeddedArrays(): ResourceCollection; + + /** Alias for allEmbeddedResourceArrays() */ + allEmbeddedResources(): ResourceCollection; + + /** + * Returns the array of embedded resources for the given key, or null if there are no embedded + * resources for this key. Each element of this arrays is in turn a Resource object. + */ + embeddedResourceArray(key: string): Resource[]; + + /** Alias for embeddedResourceArray() */ + embeddedArray(key: string): Resource[]; + + /** + * Returns the first element of the array of embedded resources for the given key or null if + * there are no embedded resources for this key. The returend object is a Resource object. + */ + embeddedResource(key: string): Resource; + + /** Alias for embeddedResource(key) */ + embedded(key: string): Resource; + + /** + * Returns the unmodified, original object that was parsed to this resource. This is rather + * uninteresting for the source object you give to the parse method (because you probably + * still have a reference to the source object) but it is a convenient way to get the part of + * the source object that corresponds to an embedded resource. + */ + original(): any; + + /** + * Returns true if the resource has any CURIEs (Compact URIs). + * + * @see http://www.w3.org/TR/2010/NOTE-curie-20101216/ + */ + hasCuries(): boolean; + + /** + * Returns the array of CURIEs. Each object in the array is a link object, which means it + * can be templated etc. See below for the link object API. + */ + curieArray(): Link[]; + + /** + * Returns the curie with the given name, if any. The returned object is a link object, which + * means it can be templated etc. See below for link object API. + */ + curie(name: string): Link; + + /** + * Returns the compact URI for the given full URL, if any + */ + reverseResolveCurie(fullUrl: string): string; + + /** + * Returns all validation issues. Validation issues are only gathered if validation has been + * turned on by calling ``halfred.enableValidation()`` before calling ``halfred.parse``. + */ + validationIssues(): any; + + /** + * Alias for validationIssues() + */ + validation(): any; + + /* + XX ... think we should NOT try to represent these things in TypeScript. + + In addition to the methods mentioned here, resource has all properties of the source object. + This is also true for embedded Resource objects. The non-HAL properties (that is, any + property except _links and _embedded) are copied over to the Resource object. This is always + a shallow copy, so modifying the a non-HAL property in the Resource object might also alter + the source object and vice versa. + + The Resource object also has the properties _links and _embedded but they might differ from + the _links/_embedded properties in the source object (Halfred applies some normalization to + them). These are not intended to be accessed by clients directly, instead, use the provided + methods to work with links and embedded resources. + */ + } + + /** @see https://github.com/basti1302/halfred#links-and-embedded-resources */ + interface ResourceCollection { + [key: string]: Resource[]; + } + + /** @see https://github.com/basti1302/halfred#links-and-embedded-resources */ + interface LinkCollection { + [rel: string]: Link[] + } + + /** + * A Link Object represents a hyperlink from the containing resource to a URI. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5 + */ + interface Link { + + /** + * The "href" property is REQUIRED. + * + * Its value is either a URI [RFC3986] or a URI Template [RFC6570]. + * + * If the value is a URI Template then the Link Object SHOULD have a + * "templated" attribute whose value is true. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.1 + */ + href: string; + + /** + * The "templated" property is OPTIONAL. + * + * Its value is boolean and SHOULD be true when the Link Object's "href" + * property is a URI Template. + * + * Its value SHOULD be considered false if it is undefined or any other + * value than true. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.2 + */ + templated?: boolean; + + /** + * The "type" property is OPTIONAL. + * + * Its value is a string used as a hint to indicate the media type + * expected when dereferencing the target resource. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.3 + */ + type?: string; + + /** + * The "deprecation" property is OPTIONAL. + * + * Its presence indicates that the link is to be deprecated (i.e. + * removed) at a future date. Its value is a URL that SHOULD provide + * further information about the deprecation. + * + * A client SHOULD provide some notification (for example, by logging a + * warning message) whenever it traverses over a link that has this + * property. The notification SHOULD include the deprecation property's + * value so that a client manitainer can easily find information about + * the deprecation. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.4 + */ + deprecation?: string; + + /** + * The "name" property is OPTIONAL. + * + * Its value MAY be used as a secondary key for selecting Link Objects + * which share the same relation type. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.5 + */ + name?: string; + + /** + * The "profile" property is OPTIONAL. + * + * Its value is a string which is a URI that hints about the profile (as + * defined by [I-D.wilde-profile-link]) of the target resource. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.6 + */ + profile?: string; + + /** + * The "title" property is OPTIONAL. + * + * Its value is a string and is intended for labelling the link with a + * human-readable identifier (as defined by [RFC5988]). + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.7 + */ + title?: string; + + /** + * The "hreflang" property is OPTIONAL. + * + * Its value is a string and is intended for indicating the language of + * the target resource (as defined by [RFC5988]). + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.8 + */ + hreflang?: string; + + } + +} From ab65bec50eba26e1f3039e44a5007dbb52b117da Mon Sep 17 00:00:00 2001 From: Daniele Frasca Date: Thu, 25 Aug 2016 10:13:39 +0100 Subject: [PATCH 128/844] added AutoScaling --- aws-sdk/aws-sdk.d.ts | 452 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 452 insertions(+) diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index cb35f34e97..652365e156 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -49,6 +49,51 @@ declare module "aws-sdk" { stack: string; } + export interface RetryDelayOption { + base?: number; + customBackoff?: (retryCount: number) => number; + } + + export interface Ebs { + snapshotId?: string; + volumeSize?: number; + volumeType?: string; + deleteOnTermination?: boolean; + iops?: number; + encrypted?: boolean; + } + + export interface BlockDeviceMapping { + virtualName?: string; + deviceName: string; + ebs?: Ebs; + noDevice?: boolean; + } + + export interface InstanceMonitoring { + spotPrice?: string; + enabled?: boolean; + } + + export interface Filter { + Name?: string; + Values?: boolean; + } + + export interface StepAdjustment { + scalingAdjustment: number; + metricIntervalLowerBound?: number; + metricIntervalUpperBound?: number; + } + + export interface Tags { + resourceId?: string; + resourceType?: string; + key: string; + value?: string; + propagateAtLaunch?: boolean; + } + export interface Services { autoscaling?: any; cloudformation?: any; @@ -147,6 +192,64 @@ declare module "aws-sdk" { updateFunctionConfiguration(params: Lambda.UpdateFunctionConfigurationParams, callback: (err: AwsError, data: any) => void): void; } + export class AutoScaling { + constructor(options?: any); + endpoint: Endpoint; + + attachInstances(params: AutoScaling.AttachInstancesParams, callback: (err: AwsError, data: any) => void): void; + attachLoadBalancers(params: AutoScaling.AttachLoadBalancersParams, callback: (err: AwsError, data: any) => void): void; + attachLoadBalancerTargetGroups(param: AutoScaling.AttachLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void; + completeLifecycleAction(param: AutoScaling.CompleteLifecycleActionParams, callback: (err: AwsError, data: any) => void): void; + createAutoScalingGroup(param: AutoScaling.CreateAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + createLaunchConfiguration(param: AutoScaling.CreateLaunchConfigurationParams, callback: (err: AwsError, data: any) => void): void; + createOrUpdateTags(param: AutoScaling.CreateOrUpdateTagsParams, callback: (err: AwsError, data: any) => void): void; + deleteAutoScalingGroup(param: AutoScaling.DeleteAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + deleteLaunchConfiguration(param: AutoScaling.DeleteLaunchConfigurationParams, callback: (err: AwsError, data: any) => void): void; + deleteLifecycleHook(param: AutoScaling.DeleteLifecycleHookParams, callback: (err: AwsError, data: any) => void): void; + deleteNotificationConfiguration(param: AutoScaling.DeleteNotificationConfigurationParams, callback: (err: AwsError, data: any) => void): void; + deletePolicy(param: AutoScaling.DeletePolicyParams, callback: (err: AwsError, data: any) => void): void; + deleteScheduledAction(param: AutoScaling.DeleteScheduledActionParams, callback: (err: AwsError, data: any) => void): void; + deleteTags(param: AutoScaling.DeleteTagsParams, callback: (err: AwsError, data: any) => void): void; + describeAccountLimits(callback: (err: AwsError, data: any) => void): void; + describeAdjustmentTypes(callback: (err: AwsError, data: any) => void): void; + describeAutoScalingGroups(param: AutoScaling.DescribeAutoScalingGroupsParams, callback: (err: AwsError, data: any) => void): void; + describeAutoScalingInstances(param: AutoScaling.DescribeAutoScalingInstancesParams, callback: (err: AwsError, data: any) => void): void; + describeAutoScalingNotificationTypes(callback: (err: AwsError, data: any) => void): void; + describeLaunchConfigurations(param: AutoScaling.DescribeLaunchConfigurationsParams, callback: (err: AwsError, data: any) => void): void; + describeLifecycleHooks(param: AutoScaling.DescribeLifecycleHooksParams, callback: (err: AwsError, data: any) => void): void; + describeLifecycleHookTypes(callback: (err: AwsError, data: any) => void): void; + describeLoadBalancers(param: AutoScaling.DescribeLoadBalancersParams, callback: (err: AwsError, data: any) => void): void; + describeLoadBalancerTargetGroups(param: AutoScaling.DescribeLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void; + describeMetricCollectionTypes(callback: (err: AwsError, data: any) => void): void; + describeNotificationConfigurations(param: AutoScaling.DescribeNotificationConfigurationsParams, callback: (err: AwsError, data: any) => void): void; + describePolicies(param: AutoScaling.DescribePoliciesParams, callback: (err: AwsError, data: any) => void): void; + describeScalingActivities(param: AutoScaling.DescribeScalingActivitiesParams, callback: (err: AwsError, data: any) => void): void; + describeScalingProcessTypes(callback: (err: AwsError, data: any) => void): void; + describeScheduledActions(param: AutoScaling.DescribeScheduledActionsParams, callback: (err: AwsError, data: any) => void): void; + describeTags(param: AutoScaling.DescribeTagsParams, callback: (err: AwsError, data: any) => void): void; + describeTerminationPolicyTypes(callback: (err: AwsError, data: any) => void): void; + detachInstances(param: AutoScaling.DetachInstancesParams, callback: (err: AwsError, data: any) => void): void; + detachLoadBalancers(param: AutoScaling.DetachLoadBalancersParams, callback: (err: AwsError, data: any) => void): void; + detachLoadBalancerTargetGroups(param: AutoScaling.DetachLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void; + disableMetricsCollection(param: AutoScaling.DisableMetricsCollectionParams, callback: (err: AwsError, data: any) => void): void; + enableMetricsCollection(param: AutoScaling.EnableMetricsCollectionParams, callback: (err: AwsError, data: any) => void): void; + enterStandby(param: AutoScaling.EnterStandbyParams, callback: (err: AwsError, data: any) => void): void; + executePolicy(param: AutoScaling.ExecutePolicyParams, callback: (err: AwsError, data: any) => void): void; + exitStandby(param: AutoScaling.ExitStandbyParams, callback: (err: AwsError, data: any) => void): void; + putLifecycleHook(param: AutoScaling.PutLifecycleHookParams, callback: (err: AwsError, data: any) => void): void; + putNotificationConfiguration(param: AutoScaling.PutNotificationConfigurationParams, callback: (err: AwsError, data: any) => void): void; + putScalingPolicy(param: AutoScaling.PutScalingPolicyParams, callback: (err: AwsError, data: any) => void): void; + putScheduledUpdateGroupAction(param: AutoScaling.PutScheduledUpdateGroupActionParams, callback: (err: AwsError, data: any) => void): void; + recordLifecycleActionHeartbeat(params: AutoScaling.RecordLifecycleActionHeartbeatParams, callback: (err: AwsError, data: any) => void): void; + resumeProcesses(params: AutoScaling.ResumeProcessesParams, callback: (err: AwsError, data: any) => void): void; + setDesiredCapacity(params: AutoScaling.SetDesiredCapacityParams, callback: (err: AwsError, data: any) => void): void; + setInstanceHealth(params: AutoScaling.SetInstanceHealthParams, callback: (err: AwsError, data: any) => void): void; + setInstanceProtection(params: AutoScaling.SetInstanceProtectionParams, callback: (err: AwsError, data: any) => void): void; + suspendProcesses(params: AutoScaling.SuspendProcessesParams, callback: (err: AwsError, data: any) => void): void; + terminateInstanceInAutoScalingGroup(params: AutoScaling.TerminateInstanceInAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + updateAutoScalingGroup(params: AutoScaling.UpdateAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + } + export class SQS { constructor(options?: any); endpoint: Endpoint; @@ -592,6 +695,355 @@ declare module "aws-sdk" { } } + export module AutoScaling { + export interface AutoScalingOptions { + params?: any; + endpoint?: string; + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: Credentials; + credentials?: Credentials; + credentialProvider?: any; + region?: string; + maxRetries?: number; + maxRedirects?: number; + sslEnabled?: boolean; + paramValidation?: boolean; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + correctClockSkew?: boolean; + s3ForcePathStyle?: boolean; + s3BucketEndpoint?: boolean; + s3DisableBodySigning?: boolean; + retryDelayOptions?: RetryDelayOption; + httpOptions?: HttpOptions; + apiVersion?: string; + apiVersions?: { [serviceName: string]: string }; + logger?: Logger; + systemClockOffset?: number; + signatureVersion?: string; + signatureCache?: boolean; + } + + export interface AttachInstancesParams { + autoScalingGroupName: string; + instanceIds: string[]; + } + + export interface AttachLoadBalancersParams { + autoScalingGroupName: string; + loadBalancerNames: string[]; + } + + export interface AttachLoadBalancerTargetGroupsParams { + autoScalingGroupName: string; + targetGroupARNs: string[]; + } + + export interface CompleteLifecycleActionParams { + autoScalingGroupName: string; + lifecycleActionResult: string; + lifecycleHookName: string; + lifecycleActionToken?: string; + instanceId?: string; + } + + export interface CreateAutoScalingGroupParams { + autoScalingGroupName: string; + minSize: number; + maxSize: number; + launchConfigurationName?: string; + instanceId?: string; + desiredCapacity?: number; + defaultCooldown?: number; + availabilityZones?: string[]; + loadBalancerNames?: string[]; + targetGroupARNs?: string[]; + healthCheckType?: string; + healthCheckGracePeriod?: number; + placementGroup?: string; + vPCZoneIdentifier?: string; + terminationPolicies?: string; + newInstancesProtectedFromScaleIn?: boolean; + tags?: Tags; + } + + export interface CreateLaunchConfigurationParams { + launchConfigurationName: string; + associatePublicIpAddress?: boolean; + imageId?: string; + keyName?: string; + securityGroups?: string[]; + classicLinkVPCId?: string; + classicLinkVPCSecurityGroups?: string[]; + userData?: string; + instanceId?: string; + instanceType?: string; + kernelId?: string; + ramdiskId?: string; + blockDeviceMappings?: BlockDeviceMapping[]; + instanceMonitoring?: InstanceMonitoring; + spotPrice?: string; + iamInstanceProfile?: string; + ebsOptimized?: boolean; + placementTenancy?: string; + } + + export interface CreateOrUpdateTagsParams { + tags: Tags[]; + } + + export interface DeleteAutoScalingGroupParams { + autoScalingGroupName: string; + forceDelete?: boolean; + } + + export interface DeleteLaunchConfigurationParams { + launchConfigurationName: string; + } + + export interface DeleteLifecycleHookParams { + autoScalingGroupName: string; + lifecycleHookName: string; + } + + export interface DeleteNotificationConfigurationParams { + autoScalingGroupName: string; + topicARN: string; + } + + export interface DeletePolicyParams { + policyName: string; + autoScalingGroupName?: string; + } + + export interface DeleteScheduledActionParams { + autoScalingGroupName: string; + scheduledActionName: string; + } + + export interface DeleteTagsParams { + tags: Tags[]; + } + + export interface DescribeAutoScalingGroupsParams { + autoScalingGroupName?: string; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeAutoScalingInstancesParams { + instanceIds?: string[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeLaunchConfigurationsParams { + launchConfigurationNames?: string[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeLifecycleHooksParams { + autoScalingGroupName: string; + lifecycleHookNames?: string[]; + } + + export interface DescribeLoadBalancersParams { + autoScalingGroupName: string; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeLoadBalancerTargetGroupsParams { + autoScalingGroupName: string; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeNotificationConfigurationsParams { + autoScalingGroupName?: string; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribePoliciesParams { + autoScalingGroupName?: string; + policyNames?: string[]; + policyTypes?: string[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeScalingActivitiesParams { + autoScalingGroupName?: string; + activityIds?: string[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeScheduledActionsParams { + autoScalingGroupName?: string; + scheduledActionNames?: string[]; + startTime?: Date; + endTime?: Date; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeTagsParams { + filters?: Filter[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DetachInstancesParams { + autoScalingGroupName: string; + shouldDecrementDesiredCapacity: boolean; + instanceIds?: string[]; + } + + export interface DetachLoadBalancersParams { + autoScalingGroupName: string; + loadBalancerNames: string; + } + + export interface DetachLoadBalancerTargetGroupsParams { + autoScalingGroupName: string; + TargetGroupARNs: string[]; + } + + export interface DisableMetricsCollectionParams { + autoScalingGroupName: string; + metrics?: string[]; + } + + export interface EnableMetricsCollectionParams { + autoScalingGroupName: string; + granularity: string; + metrics?: string[]; + } + + export interface EnterStandbyParams { + autoScalingGroupName: string; + shouldDecrementDesiredCapacity: boolean; + instanceIds?: string[]; + } + + export interface ExecutePolicyParams { + policyName: string; + autoScalingGroupName?: string; + honorCooldown?: boolean; + metricValue?: number; + breachThreshold?: number; + } + + export interface ExitStandbyParams { + autoScalingGroupName: string; + instanceIds?: string[]; + } + + export interface PutLifecycleHookParams { + autoScalingGroupName: string; + lifecycleHookName: string; + lifecycleTransition?: string; + roleARN?: string; + notificationTargetARN?: string; + notificationMetadata?: string; + heartbeatTimeout?: number; + defaultResult?: string; + } + + export interface PutNotificationConfigurationParams { + autoScalingGroupName: string; + notificationTypes: string[]; + topicARN: string; + } + + export interface PutScalingPolicyParams { + autoScalingGroupName: string; + adjustmentType: string; + policyName: string; + policyType?: string; + minAdjustmentStep?: number; + minAdjustmentMagnitude?: number; + scalingAdjustment?: number; + cooldown?: number; + metricAggregationType?: string; + stepAdjustments?: StepAdjustment[]; + estimatedInstanceWarmup: number; + } + + export interface PutScheduledUpdateGroupActionParams { + autoScalingGroupName: string; + scheduledActionName: string; + time?: Date; + startTime?: Date; + endTime?: Date; + recurrence?: string; + minSize?: number; + maxSize?: number; + desiredCapacity?: number; + } + + export interface RecordLifecycleActionHeartbeatParams { + autoScalingGroupName: string; + lifecycleHookName: string; + LifecycleActionToken?: string; + InstanceId?: string; + } + + export interface ResumeProcessesParams { + autoScalingGroupName: string; + ScalingProcesses?: string[]; + } + + export interface SetDesiredCapacityParams { + autoScalingGroupName: string; + desiredCapacity: number; + honorCooldown?: boolean; + } + + export interface SetInstanceHealthParams { + healthStatus: string; + instanceId: string; + shouldRespectGracePeriod?: boolean; + } + + export interface SetInstanceProtectionParams { + autoScalingGroupName: string; + instanceIds: string[]; + protectedFromScaleIn: boolean; + } + + export interface SuspendProcessesParams { + autoScalingGroupName: string; + scalingProcesses?: string[]; + } + + export interface TerminateInstanceInAutoScalingGroupParams { + instanceId: string; + shouldDecrementDesiredCapacity: boolean; + } + + export interface UpdateAutoScalingGroupParams { + autoScalingGroupName: string; + launchConfigurationName: string; + minSize: number; + maxSize: number; + desiredCapacity: number; + defaultCooldown: number; + availabilityZones: string[]; + healthCheckType: string; + healthCheckGracePeriod: number; + placementGroup: string; + vPCZoneIdentifier: string; + terminationPolicies: string[]; + newInstancesProtectedFromScaleIn?: boolean; + } + } + + export module SQS { export interface SqsOptions { From 2d3fcf5b626d5c0b89d1b93b5f2dd802f2036f44 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Thu, 25 Aug 2016 22:49:18 +0900 Subject: [PATCH 129/844] TypeScript-STL v1.0.1 List.sort() and its related methods are changed --- typescript-stl/typescript-stl.d.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/typescript-stl/typescript-stl.d.ts b/typescript-stl/typescript-stl.d.ts index 5a83a405cd..96d22ceb8f 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.0 +// Type definitions for TypeScript-STL v1.0.1 // Project: https://github.com/samchon/typescript-stl // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7097,6 +7097,14 @@ declare namespace std { * shall be a function pointer or a function object. */ sort(compare: (left: T, right: T) => boolean): void; + /** + * @hidden + */ + private qsort(first, last, compare); + /** + * @hidden + */ + private partition(first, last, compare); /** * @inheritdoc */ @@ -9217,7 +9225,7 @@ declare namespace std { */ erase(first: VectorReverseIterator, last: VectorReverseIterator): VectorReverseIterator; /** - * @hiddde + * @hidden */ protected erase_by_range(first: VectorIterator, last: VectorIterator): VectorIterator; /** From 992f7671e4154d5699eb050b638b28753584f993 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20S=C3=A1nchez?= Date: Thu, 25 Aug 2016 09:25:02 -0600 Subject: [PATCH 130/844] Fix #10725 - Use global / external-agnostic library pattern --- daterangepicker/daterangepicker.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/daterangepicker/daterangepicker.d.ts b/daterangepicker/daterangepicker.d.ts index f3534a197e..a86614cfe8 100644 --- a/daterangepicker/daterangepicker.d.ts +++ b/daterangepicker/daterangepicker.d.ts @@ -11,7 +11,7 @@ interface JQuery { daterangepicker(settings?: daterangepicker.Settings, callback?: (start?: string | Date | moment.Moment, end?: string | Date | moment.Moment, label?: string) => any): JQuery; } -declare module daterangepicker { +declare namespace daterangepicker { interface DatepickerEventObject extends JQueryEventObject { date: Date; @@ -164,3 +164,7 @@ declare module daterangepicker { monthNames?: string[]; } } + +declare module "daterangepicker" { + export = daterangepicker; +} From 937516aae1def4a191497fde8af0d585007d1b41 Mon Sep 17 00:00:00 2001 From: nickp10 <=> Date: Thu, 25 Aug 2016 10:29:29 -0600 Subject: [PATCH 131/844] Add parse function definition to set-cookie-parse --- set-cookie-parser/set-cookie-parser-tests.ts | 33 +++++++++++++++++--- set-cookie-parser/set-cookie-parser.d.ts | 32 ++++++++++--------- 2 files changed, 46 insertions(+), 19 deletions(-) diff --git a/set-cookie-parser/set-cookie-parser-tests.ts b/set-cookie-parser/set-cookie-parser-tests.ts index 731d38efaa..8734fdfcdb 100644 --- a/set-cookie-parser/set-cookie-parser-tests.ts +++ b/set-cookie-parser/set-cookie-parser-tests.ts @@ -1,13 +1,20 @@ /// /// -import assert = require("assert"); -import http = require("http"); -import setCookie = require("set-cookie-parser"); +import * as assert from "assert"; +import * as http from "http"; +import * as setCookie from "set-cookie-parser"; + +// Call parse function on imported object +var input = "foo=bar;"; +var cookies = setCookie.parse(input); +assert.equal(cookies.length, 1); +assert.equal(cookies[0].name, "foo"); +assert.equal(cookies[0].value, "bar"); // Required properties only test var requiredOnly = "foo=bar;"; -var cookies = setCookie(requiredOnly); +cookies = setCookie(requiredOnly); assert.equal(cookies.length, 1); assert.equal(cookies[0].name, "foo"); assert.equal(cookies[0].value, "bar"); @@ -43,3 +50,21 @@ assert.equal(cookies[0].name, "bam"); assert.equal(cookies[0].value, "baz"); assert.equal(cookies[1].name, "foo"); assert.equal(cookies[1].value, "bar"); + +// Create new cookie with only required properties +var requiredOnlyCookie: setCookie.Cookie = { + name: "Foo", + value: "Bar" +} + +// Create new cookie with all properties included optional ones +var optionalIncludedCookie: setCookie.Cookie = { + name: "Bam", + value: "Baz", + domain: ".example.com", + path: "/", + expires: new Date("Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)"), + maxAge: 1000, + httpOnly: true, + secure: true +}; diff --git a/set-cookie-parser/set-cookie-parser.d.ts b/set-cookie-parser/set-cookie-parser.d.ts index 91ca3ef2c1..3cacde6043 100644 --- a/set-cookie-parser/set-cookie-parser.d.ts +++ b/set-cookie-parser/set-cookie-parser.d.ts @@ -6,22 +6,24 @@ /// declare module "set-cookie-parser" { - import http = require("http"); + import http = require("http"); - function SetCookieParser(input: string | string[] | http.IncomingMessage): SetCookieParser.Cookie[]; + function SetCookieParser(input: string | string[] | http.IncomingMessage): SetCookieParser.Cookie[]; - namespace SetCookieParser { - interface Cookie { - name: string; - value: string; - path?: string; - expires?: Date; - maxAge?: number; - domain?: string; - secure?: boolean; - httpOnly?: boolean; - } - } + namespace SetCookieParser { + function parse(input: string | string[] | http.IncomingMessage): Cookie[]; - export = SetCookieParser; + interface Cookie { + name: string; + value: string; + path?: string; + expires?: Date; + maxAge?: number; + domain?: string; + secure?: boolean; + httpOnly?: boolean; + } + } + + export = SetCookieParser; } From 3b9f7a21648e92e6471fd87f76480b1593589665 Mon Sep 17 00:00:00 2001 From: Samir Aguiar Date: Thu, 25 Aug 2016 13:46:32 -0300 Subject: [PATCH 132/844] Add language setting and responsive option --- amcharts/AmCharts.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/amcharts/AmCharts.d.ts b/amcharts/AmCharts.d.ts index 27998956b8..f0b3aca180 100644 --- a/amcharts/AmCharts.d.ts +++ b/amcharts/AmCharts.d.ts @@ -989,6 +989,8 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val prefixesOfBigNumbers: any[]; /** Prefixes which are used to make small numbers shorter: 2μ instead of 0.000002, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e-24, prefix:"y"},{number:1e-21, prefix:"z"},{number:1e-18, prefix:"a"},{number:1e-15, prefix:"f"},{number:1e-12, prefix:"p"},{number:1e-9, prefix:"n"},{number:1e-6, prefix:"μ"},{number:1e-3, prefix:"m"}] */ prefixesOfSmallNumbers: any[]; + /** A config object for Responsive plugin. */ + responsive: any; /** Theme of a chart. Config files of themes can be found in amcharts/themes/ folder. More info about using themes. */ theme: string; /** Thousands separator. @@ -1034,6 +1036,10 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val /** Adds title to the top of the chart. Pie, Radar positions are updated so that they won't overlap. Plot area of Serial/XY chart is also updated unless autoMargins property is set to false. You can add any number of titles - each of them will be placed in a new line. To remove titles, simply clear titles array: chart.titles = []; and call chart.validateNow() method. text - text of a title size - font size color - title color alpha - title opacity bold - boolean value indicating if title should be bold. */ addTitle(text: string, size: number, color: string, alpha: number, bold: boolean); + /** Allows changing language easily. + * Note, you should include language js file from amcharts/lang or ammap/lang folder and then use variable name used in this file, like chart.language = "de"; + * Note, for maps this works differently - you use language only for country names, as there are no other strings in the maps application. */ + language(lang: string); /** Clears the chart area, intervals, etc. */ clear(); /** Removes all labels added to the chart. */ From c610ec79c45eee462d0c1e22be9ee77cff51e3c1 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 26 Aug 2016 02:11:15 +0900 Subject: [PATCH 133/844] Reflect the latest Fetch API spec --- whatwg-fetch/whatwg-fetch.d.ts | 191 +++++++++++++++++---------------- 1 file changed, 99 insertions(+), 92 deletions(-) diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index 5a428fb47b..03e5c7473e 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -1,98 +1,105 @@ -// Type definitions for fetch API +// Type definitions for Fetch API // Project: https://github.com/github/fetch -// Definitions by: Ryan Graham +// Definitions by: Ryan Graham , Kagami Sascha Rosylight // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare class Request extends Body { - constructor(input: string|Request, init?:RequestInit); - method: string; - url: string; - headers: Headers; - context: RequestContext; - referrer: string; - mode: RequestMode; - redirect: RequestRedirect; - credentials: RequestCredentials; - cache: RequestCache; -} - -interface RequestInit { - method?: string; - headers?: HeaderInit|{ [index: string]: string }; - body?: BodyInit; - mode?: RequestMode; - redirect?: RequestRedirect; - credentials?: RequestCredentials; - cache?: RequestCache; -} - -type RequestContext = - "audio" | "beacon" | "cspreport" | "download" | "embed" | - "eventsource" | "favicon" | "fetch" | "font" | "form" | "frame" | - "hyperlink" | "iframe" | "image" | "imageset" | "import" | - "internal" | "location" | "manifest" | "object" | "ping" | "plugin" | - "prefetch" | "script" | "serviceworker" | "sharedworker" | - "subresource" | "style" | "track" | "video" | "worker" | - "xmlhttprequest" | "xslt"; -type RequestMode = "same-origin" | "no-cors" | "cors"; -type RequestRedirect = "follow" | "error" | "manual"; -type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestCache = - "default" | "no-store" | "reload" | "no-cache" | - "force-cache" | "only-if-cached"; - -declare interface HeadersMap { - [index: string]: string; -} - -declare class Headers { - constructor(headers?:Headers|HeadersMap) - append(name: string, value: string): void; - delete(name: string):void; - get(name: string): string; - getAll(name: string): Array; - has(name: string): boolean; - set(name: string, value: string): void; - forEach(callback: (value: string, name: string) => void): void; -} - -declare class Body { - bodyUsed: boolean; - arrayBuffer(): Promise; - blob(): Promise; - formData(): Promise; - json(): Promise; - json(): Promise; - text(): Promise; -} - -declare class Response extends Body { - constructor(body?: BodyInit, init?: ResponseInit); - static error(): Response; - static redirect(url: string, status: number): Response; - type: ResponseType; - url: string; - status: number; - ok: boolean; - statusText: string; - headers: Headers; - clone(): Response; -} - -type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; - -interface ResponseInit { - status: number; - statusText?: string; - headers?: HeaderInit; -} - -declare type HeaderInit = Headers|Array; -declare type BodyInit = ArrayBuffer|ArrayBufferView|Blob|FormData|string; -declare type RequestInfo = Request|string; - interface Window { - fetch(url: string|Request, init?: RequestInit): Promise; + fetch(url: RequestInfo, init?: RequestInit): Promise; +} +declare var fetch: typeof window.fetch; + +declare type HeadersInit = Headers | string[][] | { [key: string]: string }; +declare class Headers { + constructor(init?: HeadersInit); + + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; + + // WebIDL pair iterator: iterable + entries(): IterableIterator<[string, string]>; + forEach(callback: (value: string, index: number, headers: Headers) => void, thisArg?: any): void; + keys(): IterableIterator; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; } -declare var fetch: typeof window.fetch; +declare type BodyInit = Blob | ArrayBufferView | ArrayBuffer | FormData /* | URLSearchParams */ | string; +interface Body { + bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; +} + +declare type RequestInfo = Request | string; +interface Request extends Body { + method: string; + url: string; + headers: Headers; + + type: "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; + destination: "" | "document" | "embed" | "font" | "image" | "manifest" | "media" | "object" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "worker" | "xslt"; + referrer: string; + referrerPolicy: ReferrerPolicy; + mode: RequestMode; + credentials: RequestCredentials; + cache: RequestCache; + redirect: RequestRedirect; + integrity: string; + + clone(): Request; +} +interface RequestInit { + method?: string; + headers?: HeadersInit; + body?: BodyInit; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + mode?: RequestMode; + credentials?: RequestCredentials; + cache?: RequestCache; + redirect?: RequestRedirect; + integrity?: string; + window?: any; +} +interface RequestConstructor { + new (input: RequestInfo, init?: RequestInit): Request; +} +declare var Request: RequestConstructor; + +type RequestMode = "same-origin" | "no-cors" | "cors"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; +type RequestRedirect = "follow" | "error" | "manual"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "unsafe-url"; + +interface Response extends Body { + type: "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; + url: string; + redirected: boolean; + status: number; + ok: boolean; + statusText: string; + headers: Headers; + body: any /*ReadableStream | null*/; + trailer: Promise; + + clone(): Response; +} +interface ResponseInit { + status?: number; + statusText?: number; + headers?: HeadersInit; +} +interface ResponseConstructor { + new (body?: BodyInit, init?: ResponseInit): Response; + + error(): Response; + redirect(url: string, status?: number): Response; +} +declare var Response: ResponseConstructor; From 4d273e48487d1154719e7ec0da4902d3564cd74c Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 26 Aug 2016 02:29:25 +0900 Subject: [PATCH 134/844] Add missing enum items --- whatwg-fetch/whatwg-fetch.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index 03e5c7473e..d9aeca1fe3 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -72,11 +72,11 @@ interface RequestConstructor { } declare var Request: RequestConstructor; -type RequestMode = "same-origin" | "no-cors" | "cors"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached"; type RequestRedirect = "follow" | "error" | "manual"; -type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "unsafe-url"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url"; interface Response extends Body { type: "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; From 46a63785b7cf89900d1cdd2ad2b507d69c314c70 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 26 Aug 2016 02:35:59 +0900 Subject: [PATCH 135/844] Remove null union as TS stable does not support it --- whatwg-fetch/whatwg-fetch.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index d9aeca1fe3..a5fe21dc09 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -14,7 +14,7 @@ declare class Headers { append(name: string, value: string): void; delete(name: string): void; - get(name: string): string | null; + get(name: string): string; // | null; (TS 2.0 strict null check) has(name: string): boolean; set(name: string, value: string): void; From ad7532875359ba339ac65d0a62c4ad312487e4f7 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 26 Aug 2016 02:38:42 +0900 Subject: [PATCH 136/844] statusText fix --- whatwg-fetch/whatwg-fetch.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index a5fe21dc09..d6cfd2638a 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -93,7 +93,7 @@ interface Response extends Body { } interface ResponseInit { status?: number; - statusText?: number; + statusText?: string; headers?: HeadersInit; } interface ResponseConstructor { From 2d310f938eb552eadca2b14a1299c73172bb1924 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 26 Aug 2016 03:02:42 +0900 Subject: [PATCH 137/844] HeadersMap was essentially a DOMStringMap ... and TS 2.0 even will not require the type --- whatwg-fetch/whatwg-fetch-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/whatwg-fetch/whatwg-fetch-tests.ts b/whatwg-fetch/whatwg-fetch-tests.ts index 090e114b5d..3f23abe914 100644 --- a/whatwg-fetch/whatwg-fetch-tests.ts +++ b/whatwg-fetch/whatwg-fetch-tests.ts @@ -7,7 +7,7 @@ function test_HeadersCopiedFromHeaders() { } function test_HeadersCopiedFromHash() { - var source:HeadersMap = { + var source: DOMStringMap = { 'Content-Type': 'application/json' }; return new Headers(source); From cc19e43b3d7eb0f5b598fd3ec17cc0edf1e6cf22 Mon Sep 17 00:00:00 2001 From: Sebastian Rogers Date: Thu, 25 Aug 2016 16:55:59 -0500 Subject: [PATCH 138/844] Added "identifier" property to PIXI.interaction.InteractionData. --- pixi.js/pixi.js.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/pixi.js/pixi.js.d.ts b/pixi.js/pixi.js.d.ts index dfccd33431..d8e6bf86d7 100644 --- a/pixi.js/pixi.js.d.ts +++ b/pixi.js/pixi.js.d.ts @@ -1456,6 +1456,7 @@ declare namespace PIXI { global: Point; target: DisplayObject; originalEvent: Event; + identifier: number; getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; From 8191eb49a6223d6cb5f9e5a38625983a62a01f4a Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 26 Aug 2016 10:16:51 +0900 Subject: [PATCH 139/844] type aliases --- whatwg-fetch/whatwg-fetch.d.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index d6cfd2638a..21baca126f 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -42,8 +42,8 @@ interface Request extends Body { url: string; headers: Headers; - type: "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; - destination: "" | "document" | "embed" | "font" | "image" | "manifest" | "media" | "object" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "worker" | "xslt"; + type: RequestType + destination: RequestDestination; referrer: string; referrerPolicy: ReferrerPolicy; mode: RequestMode; @@ -72,6 +72,8 @@ interface RequestConstructor { } declare var Request: RequestConstructor; +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; +type RequestDestination = "" | "document" | "embed" | "font" | "image" | "manifest" | "media" | "object" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "worker" | "xslt"; type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; type RequestCredentials = "omit" | "same-origin" | "include"; type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached"; @@ -79,7 +81,7 @@ type RequestRedirect = "follow" | "error" | "manual"; type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url"; interface Response extends Body { - type: "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; + type: ResponseType; url: string; redirected: boolean; status: number; @@ -103,3 +105,5 @@ interface ResponseConstructor { redirect(url: string, status?: number): Response; } declare var Response: ResponseConstructor; + +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; From f7b4206312a7a2447b1cef9eeca2d9bcdc00cd41 Mon Sep 17 00:00:00 2001 From: Keisuke Kan <9renpoto@gmail.com> Date: Fri, 26 Aug 2016 11:09:07 +0900 Subject: [PATCH 140/844] Fixed interface Options --- gulp-uglify/gulp-uglify-tests.ts | 2 +- gulp-uglify/gulp-uglify.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gulp-uglify/gulp-uglify-tests.ts b/gulp-uglify/gulp-uglify-tests.ts index 01cfb06f9e..6a1cf1281d 100644 --- a/gulp-uglify/gulp-uglify-tests.ts +++ b/gulp-uglify/gulp-uglify-tests.ts @@ -14,7 +14,7 @@ gulp.task('compress2', function() { var tsResult = gulp.src('lib/*.ts') .pipe(uglify({ mangle: false, - preserverComments: "some", + preserveComments: "some", compress: false, output: { max_line_len: 300 diff --git a/gulp-uglify/gulp-uglify.d.ts b/gulp-uglify/gulp-uglify.d.ts index 13eda63706..60cd8f11ea 100644 --- a/gulp-uglify/gulp-uglify.d.ts +++ b/gulp-uglify/gulp-uglify.d.ts @@ -32,7 +32,7 @@ declare module "gulp-uglify" { * some - Preserve comments that start with a bang (!) or include a Closure Compiler directive (@preserve, @license, @cc_on) * function - Specify your own comment preservation function. You will be passed the current node and the current comment and are expected to return either true or false. */ - preserverComments?: string|((node: any, comment: UglifyJS.Tokenizer) => boolean); + preserveComments?: string|((node: any, comment: UglifyJS.Tokenizer) => boolean); } } From fa7b9cfa56c6c077dc402b1f1f407a192bf74b34 Mon Sep 17 00:00:00 2001 From: Bahman Nikkhahan Date: Fri, 26 Aug 2016 12:50:47 +1000 Subject: [PATCH 141/844] Typing for notify.js --- notify.js/notify.js.d.ts | 124 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 notify.js/notify.js.d.ts diff --git a/notify.js/notify.js.d.ts b/notify.js/notify.js.d.ts new file mode 100644 index 0000000000..dc50230b5b --- /dev/null +++ b/notify.js/notify.js.d.ts @@ -0,0 +1,124 @@ +//Created by Bahman Nikkhahan https://github.com/bahman616 +interface NotificationOptions { + // whether to hide the notification on click + clickToHide: boolean; + // whether to auto-hide the notification + autoHide: boolean; + // if autoHide, hide after milliseconds + autoHideDelay: number; + // show the arrow pointing at the element + arrowShow: boolean; + // arrow size in pixels + arrowSize: number; + // position defines the notification position though uses the defaults below + position: string; + // default positions + elementPosition: string; + globalPosition: string; + // default style + style: string; + // default class (string or [string]) + className: string; + // show animation + showAnimation: string; + // show animation duration + showDuration: number; + // hide animation + hideAnimation: string; + // hide animation duration + hideDuration: number; + // padding between element and notification + gap: number; +} + +interface JQueryStaticNotify { + /** + * notify user + * @param element a jquery element + * @param notificationdata global notification data + * @param options notification options + */ + (element?: any, notificationdata?: any, options?: NotificationOptions): JQueryStatic; + + /** + * notify user + * @param styleName style name + * @param styleDefinition style definition object + */ + addStyle(styleName: string, styleDefinition: any); + + /** + * notify user + * @param styleName style name + */ + removeStyle(styleName: string); + + /** + * notify user + * @param styleName style name + */ + getStyle(styleName: string); + + /** + * notify user + * @param cssText css text to insert + */ + insertCSS(cssText: string); + + /** + * notify user + * @param options notification iptions + */ + defaults(options: NotificationOptions) +} + +interface JQueryStatic { + notify: JQueryStaticNotify; +} + +interface JQueryNotify { + /** + * notify user + * @param element a jquery element + * @param notificationdata global notification data + * @param options notification options + */ + (element?: any, notificationdata?: any, options?: NotificationOptions): JQuery; + + /** + * notify user + * @param styleName style name + * @param styleDefinition style definition object + */ + addStyle(styleName: string, styleDefinition: any); + + /** + * notify user + * @param styleName style name + */ + removeStyle(styleName: string); + + /** + * notify user + * @param styleName style name + */ + getStyle(styleName: string); + + /** + * notify user + * @param cssText css text to insert + */ + insertCSS(cssText: string); + + /** + * notify user + * @param options notification iptions + */ + defaults(options: NotificationOptions) + +} + +interface JQuery { + notify: JQueryStaticNotify; +} + From 4ce23b34dbd3aeb0ab4eb4f60a62c0f248a57e74 Mon Sep 17 00:00:00 2001 From: Leo Liang Date: Fri, 26 Aug 2016 15:12:22 +0800 Subject: [PATCH 142/844] pg 6.1.0 --- pg-pool/pg-pool-tests.ts | 42 +++++++++++++++++++++++++++++++++ pg-pool/pg-pool.d.ts | 50 ++++++++++++++++++++++++++++++++++++++++ pg/pg-tests.ts | 30 ++++++++++++++++++++++++ pg/pg.d.ts | 11 +++++++-- 4 files changed, 131 insertions(+), 2 deletions(-) create mode 100644 pg-pool/pg-pool-tests.ts create mode 100644 pg-pool/pg-pool.d.ts diff --git a/pg-pool/pg-pool-tests.ts b/pg-pool/pg-pool-tests.ts new file mode 100644 index 0000000000..96de93d667 --- /dev/null +++ b/pg-pool/pg-pool-tests.ts @@ -0,0 +1,42 @@ +/// +import {Pool} from "pg-pool"; + +let pool = new Pool() + +//you can pass properties to the pool +//these properties are passed unchanged to both the node-postgres Client constructor +//and the node-pool (https://github.com/coopernurse/node-pool) constructor +//allowing you to fully configure the behavior of both +let pool2 = new Pool({ + database: 'postgres', + user: 'brianc', + password: 'secret!', + port: 5432, + ssl: true, + max: 20, //set pool max size to 20 + min: 4, //set min pool size to 4 + idleTimeoutMillis: 1000 //close idle clients after 1 second +}) + +pool.connect().then(client => { + client.query('select $1::text as name', ['pg-pool']).then(res => { + client.release() + console.log('hello from', res.rows[0].name) + }) + .catch(e => { + client.release() + console.error('query error', e.message, e.stack) + }) +}) + +async function helperTest() { + const time = await pool.query('SELECT NOW()'); + const name = await pool.query('select $1::text as name', ['brianc']); + console.log(name.rows[0].name, 'says hello at', time.rows[0].name); +} + +pool.query('SELECT $1::text as name', ['brianc'], function (err, res) { + console.log(res.rows[0].name) // brianc +}) + +pool.end(); \ No newline at end of file diff --git a/pg-pool/pg-pool.d.ts b/pg-pool/pg-pool.d.ts new file mode 100644 index 0000000000..7762425963 --- /dev/null +++ b/pg-pool/pg-pool.d.ts @@ -0,0 +1,50 @@ +// Type definitions for pg-pool +// Project: https://github.com/brianc/node-pg-pool +// Definitions by: Leo Liang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module "pg-pool" { + import * as events from "events"; + import * as stream from "stream"; + import * as pg from "pg"; + + export interface PoolConfig extends pg.ClientConfig { + // properties from module 'node-pool' + max?: number; + min?: number; + refreshIdle?: boolean; + idleTimeoutMillis?: number; + reapIntervalMillis?: number; + returnToHead?: boolean; + } + + export class Pool extends events.EventEmitter { + + constructor(); + + // `new Pool('pg://user@localhost/mydb')` is not allowed. + // But it passes type check because of issue: + // https://github.com/Microsoft/TypeScript/issues/7485 + constructor(config: PoolConfig); + + connect(): Promise; + connect(callback: (err: Error, client: pg.Client, done: () => void) => void): void; + + end(): Promise; + + query(queryText: string): Promise; + query(queryText: string, values: any[]): Promise; + + query(queryText: string, callback: (err: Error, result: pg.QueryResult) => void): void; + query(queryText: string, values: any[], callback: (err: Error, result: pg.QueryResult) => void): void; + + public on(event: "error", listener: (err: Error, client: pg.Client) => void): this; + public on(event: "connect", listener: (client: pg.Client) => void): this; + public on(event: "acquire", listener: (client: pg.Client) => void): this; + public on(event: string, listener: Function): this; + } + +} diff --git a/pg/pg-tests.ts b/pg/pg-tests.ts index 559c6183fc..6c919bd132 100644 --- a/pg/pg-tests.ts +++ b/pg/pg-tests.ts @@ -42,3 +42,33 @@ client.connect((err) => { }); return null; }); + +// client pooling + +var config = { + user: 'foo', //env var: PGUSER + database: 'my_db', //env var: PGDATABASE + password: 'secret', //env var: PGPASSWORD + port: 5432, //env var: PGPORT + max: 10, // max number of clients in the pool + idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed +}; +var pool = new pg.Pool(config); + +pool.connect(function(err, client, done) { + if(err) { + return console.error('error fetching client from pool', err); + } + client.query('SELECT $1::int AS number', ['1'], function(err, result) { + done(); + + if(err) { + return console.error('error running query', err); + } + console.log(result.rows[0].number); + }); +}); + +pool.on('error', function (err, client) { + console.error('idle client error', err.message, err.stack) +}) \ No newline at end of file diff --git a/pg/pg.d.ts b/pg/pg.d.ts index 592d782610..4df1e63104 100644 --- a/pg/pg.d.ts +++ b/pg/pg.d.ts @@ -1,14 +1,17 @@ -// Type definitions for pg +// Type definitions for pg 6.1.0 // Project: https://github.com/brianc/node-postgres // Definitions by: Phips Peter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// declare module "pg" { import events = require("events"); import stream = require("stream"); + export {Pool, PoolConfig} from "pg-pool"; + export function connect(connection: string, callback: (err: Error, client: Client, done: (err?: any) => void) => void): void; export function connect(config: ClientConfig, callback: (err: Error, client: Client, done: (err?: any) => void) => void): void; export function end(): void; @@ -56,6 +59,10 @@ declare module "pg" { connect(callback?: (err:Error) => void): void; end(): void; + release(): void; + + query(queryText: string): Promise; + query(queryText: string, values: any[]): Promise; query(queryText: string, callback?: (err: Error, result: QueryResult) => void): Query; query(config: QueryConfig, callback?: (err: Error, result: QueryResult) => void): Query; @@ -86,7 +93,7 @@ declare module "pg" { public on(event: string, listener: Function): this; } - namespace types { + export namespace types { function setTypeParser(typeId: number, parser: (value: string) => T): void; } } From 026d5663468d0e7f7337f3164fa92a8ff118f27d Mon Sep 17 00:00:00 2001 From: Hristian Hristov Date: Fri, 26 Aug 2016 13:04:25 +0100 Subject: [PATCH 143/844] Node.d.ts: Change definition for module process to be consistent with other declarations --- node/node.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index 280f17e045..731b136585 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2627,6 +2627,5 @@ declare module "constants" { } declare module "process" { - var p: NodeJS.Process; - export default p; + export = process; } \ No newline at end of file From aa7fb007db039fb20f2db6cf104d1c8c27e59ae7 Mon Sep 17 00:00:00 2001 From: Daniele Frasca Date: Fri, 26 Aug 2016 16:27:49 +0100 Subject: [PATCH 144/844] fixed the property name with upper case letter --- aws-sdk/aws-sdk.d.ts | 354 +++++++++++++++++++++---------------------- 1 file changed, 177 insertions(+), 177 deletions(-) diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index 652365e156..6f5ced6cd3 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -726,320 +726,320 @@ declare module "aws-sdk" { } export interface AttachInstancesParams { - autoScalingGroupName: string; - instanceIds: string[]; + AutoScalingGroupName: string; + InstanceIds: string[]; } export interface AttachLoadBalancersParams { - autoScalingGroupName: string; - loadBalancerNames: string[]; + AutoScalingGroupName: string; + LoadBalancerNames: string[]; } export interface AttachLoadBalancerTargetGroupsParams { - autoScalingGroupName: string; - targetGroupARNs: string[]; + AutoScalingGroupName: string; + TargetGroupARNs: string[]; } export interface CompleteLifecycleActionParams { - autoScalingGroupName: string; - lifecycleActionResult: string; - lifecycleHookName: string; + AutoScalingGroupName: string; + LifecycleActionResult: string; + LifecycleHookName: string; lifecycleActionToken?: string; - instanceId?: string; + InstanceId?: string; } export interface CreateAutoScalingGroupParams { - autoScalingGroupName: string; - minSize: number; - maxSize: number; - launchConfigurationName?: string; - instanceId?: string; - desiredCapacity?: number; - defaultCooldown?: number; - availabilityZones?: string[]; - loadBalancerNames?: string[]; - targetGroupARNs?: string[]; - healthCheckType?: string; - healthCheckGracePeriod?: number; - placementGroup?: string; - vPCZoneIdentifier?: string; - terminationPolicies?: string; - newInstancesProtectedFromScaleIn?: boolean; - tags?: Tags; + AutoScalingGroupName: string; + MinSize: number; + MaxSize: number; + LaunchConfigurationName?: string; + InstanceId?: string; + DesiredCapacity?: number; + DefaultCooldown?: number; + AvailabilityZones?: string[]; + LoadBalancerNames?: string[]; + TargetGroupARNs?: string[]; + HealthCheckType?: string; + HealthCheckGracePeriod?: number; + PlacementGroup?: string; + VPCZoneIdentifier?: string; + TerminationPolicies?: string; + NewInstancesProtectedFromScaleIn?: boolean; + Tags?: Tags; } export interface CreateLaunchConfigurationParams { - launchConfigurationName: string; - associatePublicIpAddress?: boolean; - imageId?: string; - keyName?: string; - securityGroups?: string[]; - classicLinkVPCId?: string; - classicLinkVPCSecurityGroups?: string[]; - userData?: string; - instanceId?: string; - instanceType?: string; - kernelId?: string; - ramdiskId?: string; - blockDeviceMappings?: BlockDeviceMapping[]; - instanceMonitoring?: InstanceMonitoring; - spotPrice?: string; - iamInstanceProfile?: string; - ebsOptimized?: boolean; - placementTenancy?: string; + LaunchConfigurationName: string; + AssociatePublicIpAddress?: boolean; + ImageId?: string; + KeyName?: string; + SecurityGroups?: string[]; + ClassicLinkVPCId?: string; + ClassicLinkVPCSecurityGroups?: string[]; + UserData?: string; + InstanceId?: string; + InstanceType?: string; + KernelId?: string; + RamdiskId?: string; + BlockDeviceMappings?: BlockDeviceMapping[]; + InstanceMonitoring?: InstanceMonitoring; + SpotPrice?: string; + IamInstanceProfile?: string; + EbsOptimized?: boolean; + PlacementTenancy?: string; } export interface CreateOrUpdateTagsParams { - tags: Tags[]; + Tags: Tags[]; } export interface DeleteAutoScalingGroupParams { - autoScalingGroupName: string; - forceDelete?: boolean; + AutoScalingGroupName: string; + ForceDelete?: boolean; } export interface DeleteLaunchConfigurationParams { - launchConfigurationName: string; + LaunchConfigurationName: string; } export interface DeleteLifecycleHookParams { - autoScalingGroupName: string; - lifecycleHookName: string; + AutoScalingGroupName: string; + LifecycleHookName: string; } export interface DeleteNotificationConfigurationParams { - autoScalingGroupName: string; - topicARN: string; + AutoScalingGroupName: string; + TopicARN: string; } export interface DeletePolicyParams { - policyName: string; - autoScalingGroupName?: string; + PolicyName: string; + AutoScalingGroupName?: string; } export interface DeleteScheduledActionParams { - autoScalingGroupName: string; - scheduledActionName: string; + AutoScalingGroupName: string; + ScheduledActionName: string; } export interface DeleteTagsParams { - tags: Tags[]; + Tags: Tags[]; } export interface DescribeAutoScalingGroupsParams { - autoScalingGroupName?: string; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + NextToken?: string; + MaxRecords?: number; } export interface DescribeAutoScalingInstancesParams { - instanceIds?: string[]; - nextToken?: string; - maxRecords?: number; + InstanceIds?: string[]; + NextToken?: string; + MaxRecords?: number; } export interface DescribeLaunchConfigurationsParams { - launchConfigurationNames?: string[]; - nextToken?: string; - maxRecords?: number; + LaunchConfigurationNames?: string[]; + NextToken?: string; + MaxRecords?: number; } export interface DescribeLifecycleHooksParams { - autoScalingGroupName: string; - lifecycleHookNames?: string[]; + AutoScalingGroupName: string; + LifecycleHookNames?: string[]; } export interface DescribeLoadBalancersParams { - autoScalingGroupName: string; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName: string; + NextToken?: string; + MaxRecords?: number; } export interface DescribeLoadBalancerTargetGroupsParams { - autoScalingGroupName: string; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName: string; + NextToken?: string; + MaxRecords?: number; } export interface DescribeNotificationConfigurationsParams { - autoScalingGroupName?: string; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + NextToken?: string; + MaxRecords?: number; } export interface DescribePoliciesParams { - autoScalingGroupName?: string; - policyNames?: string[]; - policyTypes?: string[]; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + PolicyNames?: string[]; + PolicyTypes?: string[]; + NextToken?: string; + MaxRecords?: number; } export interface DescribeScalingActivitiesParams { - autoScalingGroupName?: string; - activityIds?: string[]; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + ActivityIds?: string[]; + NextToken?: string; + MaxRecords?: number; } export interface DescribeScheduledActionsParams { - autoScalingGroupName?: string; - scheduledActionNames?: string[]; - startTime?: Date; - endTime?: Date; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + ScheduledActionNames?: string[]; + StartTime?: Date; + EndTime?: Date; + NextToken?: string; + MaxRecords?: number; } export interface DescribeTagsParams { - filters?: Filter[]; - nextToken?: string; - maxRecords?: number; + Filters?: Filter[]; + NextToken?: string; + MaxRecords?: number; } export interface DetachInstancesParams { - autoScalingGroupName: string; - shouldDecrementDesiredCapacity: boolean; - instanceIds?: string[]; + AutoScalingGroupName: string; + ShouldDecrementDesiredCapacity: boolean; + InstanceIds?: string[]; } export interface DetachLoadBalancersParams { - autoScalingGroupName: string; - loadBalancerNames: string; + AutoScalingGroupName: string; + LoadBalancerNames: string; } export interface DetachLoadBalancerTargetGroupsParams { - autoScalingGroupName: string; + AutoScalingGroupName: string; TargetGroupARNs: string[]; } export interface DisableMetricsCollectionParams { - autoScalingGroupName: string; - metrics?: string[]; + AutoScalingGroupName: string; + Metrics?: string[]; } export interface EnableMetricsCollectionParams { - autoScalingGroupName: string; - granularity: string; - metrics?: string[]; + AutoScalingGroupName: string; + Granularity: string; + Metrics?: string[]; } export interface EnterStandbyParams { - autoScalingGroupName: string; - shouldDecrementDesiredCapacity: boolean; - instanceIds?: string[]; + AutoScalingGroupName: string; + ShouldDecrementDesiredCapacity: boolean; + InstanceIds?: string[]; } export interface ExecutePolicyParams { - policyName: string; - autoScalingGroupName?: string; - honorCooldown?: boolean; - metricValue?: number; - breachThreshold?: number; + PolicyName: string; + AutoScalingGroupName?: string; + HonorCooldown?: boolean; + MetricValue?: number; + BreachThreshold?: number; } export interface ExitStandbyParams { - autoScalingGroupName: string; - instanceIds?: string[]; + AutoScalingGroupName: string; + InstanceIds?: string[]; } export interface PutLifecycleHookParams { - autoScalingGroupName: string; - lifecycleHookName: string; - lifecycleTransition?: string; - roleARN?: string; - notificationTargetARN?: string; - notificationMetadata?: string; - heartbeatTimeout?: number; - defaultResult?: string; + AutoScalingGroupName: string; + LifecycleHookName: string; + LifecycleTransition?: string; + RoleARN?: string; + NotificationTargetARN?: string; + NotificationMetadata?: string; + HeartbeatTimeout?: number; + DefaultResult?: string; } export interface PutNotificationConfigurationParams { - autoScalingGroupName: string; - notificationTypes: string[]; - topicARN: string; + AutoScalingGroupName: string; + NotificationTypes: string[]; + TopicARN: string; } export interface PutScalingPolicyParams { - autoScalingGroupName: string; - adjustmentType: string; - policyName: string; - policyType?: string; - minAdjustmentStep?: number; - minAdjustmentMagnitude?: number; - scalingAdjustment?: number; - cooldown?: number; - metricAggregationType?: string; - stepAdjustments?: StepAdjustment[]; - estimatedInstanceWarmup: number; + AutoScalingGroupName: string; + AdjustmentType: string; + PolicyName: string; + PolicyType?: string; + MinAdjustmentStep?: number; + MinAdjustmentMagnitude?: number; + ScalingAdjustment?: number; + Cooldown?: number; + MetricAggregationType?: string; + StepAdjustments?: StepAdjustment[]; + EstimatedInstanceWarmup: number; } export interface PutScheduledUpdateGroupActionParams { - autoScalingGroupName: string; - scheduledActionName: string; - time?: Date; - startTime?: Date; - endTime?: Date; - recurrence?: string; - minSize?: number; - maxSize?: number; - desiredCapacity?: number; + AutoScalingGroupName: string; + ScheduledActionName: string; + Time?: Date; + StartTime?: Date; + EndTime?: Date; + Recurrence?: string; + MinSize?: number; + MaxSize?: number; + DesiredCapacity?: number; } export interface RecordLifecycleActionHeartbeatParams { - autoScalingGroupName: string; - lifecycleHookName: string; + AutoScalingGroupName: string; + LifecycleHookName: string; LifecycleActionToken?: string; InstanceId?: string; } export interface ResumeProcessesParams { - autoScalingGroupName: string; + AutoScalingGroupName: string; ScalingProcesses?: string[]; } export interface SetDesiredCapacityParams { - autoScalingGroupName: string; - desiredCapacity: number; - honorCooldown?: boolean; + AutoScalingGroupName: string; + DesiredCapacity: number; + HonorCooldown?: boolean; } export interface SetInstanceHealthParams { - healthStatus: string; - instanceId: string; - shouldRespectGracePeriod?: boolean; + HealthStatus: string; + InstanceId: string; + ShouldRespectGracePeriod?: boolean; } export interface SetInstanceProtectionParams { - autoScalingGroupName: string; - instanceIds: string[]; - protectedFromScaleIn: boolean; + AutoScalingGroupName: string; + InstanceIds: string[]; + ProtectedFromScaleIn: boolean; } export interface SuspendProcessesParams { - autoScalingGroupName: string; - scalingProcesses?: string[]; + AutoScalingGroupName: string; + ScalingProcesses?: string[]; } export interface TerminateInstanceInAutoScalingGroupParams { - instanceId: string; - shouldDecrementDesiredCapacity: boolean; + InstanceId: string; + ShouldDecrementDesiredCapacity: boolean; } export interface UpdateAutoScalingGroupParams { - autoScalingGroupName: string; - launchConfigurationName: string; - minSize: number; - maxSize: number; - desiredCapacity: number; - defaultCooldown: number; - availabilityZones: string[]; - healthCheckType: string; - healthCheckGracePeriod: number; - placementGroup: string; - vPCZoneIdentifier: string; - terminationPolicies: string[]; - newInstancesProtectedFromScaleIn?: boolean; + AutoScalingGroupName: string; + LaunchConfigurationName: string; + MinSize: number; + MaxSize: number; + DesiredCapacity: number; + DefaultCooldown: number; + AvailabilityZones: string[]; + HealthCheckType: string; + HealthCheckGracePeriod: number; + PlacementGroup: string; + VPCZoneIdentifier: string; + TerminationPolicies: string[]; + NewInstancesProtectedFromScaleIn?: boolean; } } From df2e17b0a951123fa1ba1e8b673073c4aaef25ed Mon Sep 17 00:00:00 2001 From: Daniele Frasca Date: Fri, 26 Aug 2016 16:31:19 +0100 Subject: [PATCH 145/844] fixed the first letter of the property to be uppecase --- aws-sdk/aws-sdk.d.ts | 714 +++++++++++++++++++++---------------------- 1 file changed, 357 insertions(+), 357 deletions(-) diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index 6f5ced6cd3..4ed550251b 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -55,24 +55,24 @@ declare module "aws-sdk" { } export interface Ebs { - snapshotId?: string; - volumeSize?: number; - volumeType?: string; - deleteOnTermination?: boolean; - iops?: number; - encrypted?: boolean; + SnapshotId?: string; + VolumeSize?: number; + VolumeType?: string; + DeleteOnTermination?: boolean; + Iops?: number; + Encrypted?: boolean; } export interface BlockDeviceMapping { - virtualName?: string; - deviceName: string; - ebs?: Ebs; - noDevice?: boolean; + VirtualName?: string; + DeviceName: string; + Ebs?: Ebs; + NoDevice?: boolean; } export interface InstanceMonitoring { - spotPrice?: string; - enabled?: boolean; + SpotPrice?: string; + Enabled?: boolean; } export interface Filter { @@ -696,353 +696,353 @@ declare module "aws-sdk" { } export module AutoScaling { - export interface AutoScalingOptions { - params?: any; - endpoint?: string; - accessKeyId?: string; - secretAccessKey?: string; - sessionToken?: Credentials; - credentials?: Credentials; - credentialProvider?: any; - region?: string; - maxRetries?: number; - maxRedirects?: number; - sslEnabled?: boolean; - paramValidation?: boolean; - computeChecksums?: boolean; - convertResponseTypes?: boolean; - correctClockSkew?: boolean; - s3ForcePathStyle?: boolean; - s3BucketEndpoint?: boolean; - s3DisableBodySigning?: boolean; - retryDelayOptions?: RetryDelayOption; - httpOptions?: HttpOptions; - apiVersion?: string; - apiVersions?: { [serviceName: string]: string }; - logger?: Logger; - systemClockOffset?: number; - signatureVersion?: string; - signatureCache?: boolean; - } - - export interface AttachInstancesParams { - AutoScalingGroupName: string; - InstanceIds: string[]; - } - - export interface AttachLoadBalancersParams { - AutoScalingGroupName: string; - LoadBalancerNames: string[]; - } - - export interface AttachLoadBalancerTargetGroupsParams { - AutoScalingGroupName: string; - TargetGroupARNs: string[]; - } - - export interface CompleteLifecycleActionParams { - AutoScalingGroupName: string; - LifecycleActionResult: string; - LifecycleHookName: string; - lifecycleActionToken?: string; - InstanceId?: string; - } - - export interface CreateAutoScalingGroupParams { - AutoScalingGroupName: string; - MinSize: number; - MaxSize: number; - LaunchConfigurationName?: string; - InstanceId?: string; - DesiredCapacity?: number; - DefaultCooldown?: number; - AvailabilityZones?: string[]; - LoadBalancerNames?: string[]; - TargetGroupARNs?: string[]; - HealthCheckType?: string; - HealthCheckGracePeriod?: number; - PlacementGroup?: string; - VPCZoneIdentifier?: string; - TerminationPolicies?: string; - NewInstancesProtectedFromScaleIn?: boolean; - Tags?: Tags; - } - - export interface CreateLaunchConfigurationParams { - LaunchConfigurationName: string; - AssociatePublicIpAddress?: boolean; - ImageId?: string; - KeyName?: string; - SecurityGroups?: string[]; - ClassicLinkVPCId?: string; - ClassicLinkVPCSecurityGroups?: string[]; - UserData?: string; - InstanceId?: string; - InstanceType?: string; - KernelId?: string; - RamdiskId?: string; - BlockDeviceMappings?: BlockDeviceMapping[]; - InstanceMonitoring?: InstanceMonitoring; - SpotPrice?: string; - IamInstanceProfile?: string; - EbsOptimized?: boolean; - PlacementTenancy?: string; - } - - export interface CreateOrUpdateTagsParams { - Tags: Tags[]; - } - - export interface DeleteAutoScalingGroupParams { - AutoScalingGroupName: string; - ForceDelete?: boolean; - } - - export interface DeleteLaunchConfigurationParams { - LaunchConfigurationName: string; - } - - export interface DeleteLifecycleHookParams { - AutoScalingGroupName: string; - LifecycleHookName: string; - } - - export interface DeleteNotificationConfigurationParams { - AutoScalingGroupName: string; - TopicARN: string; - } - - export interface DeletePolicyParams { - PolicyName: string; - AutoScalingGroupName?: string; - } - - export interface DeleteScheduledActionParams { - AutoScalingGroupName: string; - ScheduledActionName: string; - } - - export interface DeleteTagsParams { - Tags: Tags[]; - } - - export interface DescribeAutoScalingGroupsParams { - AutoScalingGroupName?: string; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeAutoScalingInstancesParams { - InstanceIds?: string[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeLaunchConfigurationsParams { - LaunchConfigurationNames?: string[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeLifecycleHooksParams { - AutoScalingGroupName: string; - LifecycleHookNames?: string[]; - } - - export interface DescribeLoadBalancersParams { - AutoScalingGroupName: string; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeLoadBalancerTargetGroupsParams { - AutoScalingGroupName: string; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeNotificationConfigurationsParams { - AutoScalingGroupName?: string; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribePoliciesParams { - AutoScalingGroupName?: string; - PolicyNames?: string[]; - PolicyTypes?: string[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeScalingActivitiesParams { - AutoScalingGroupName?: string; - ActivityIds?: string[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeScheduledActionsParams { - AutoScalingGroupName?: string; - ScheduledActionNames?: string[]; - StartTime?: Date; - EndTime?: Date; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeTagsParams { - Filters?: Filter[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DetachInstancesParams { - AutoScalingGroupName: string; - ShouldDecrementDesiredCapacity: boolean; - InstanceIds?: string[]; - } - - export interface DetachLoadBalancersParams { - AutoScalingGroupName: string; - LoadBalancerNames: string; - } - - export interface DetachLoadBalancerTargetGroupsParams { - AutoScalingGroupName: string; - TargetGroupARNs: string[]; - } - - export interface DisableMetricsCollectionParams { - AutoScalingGroupName: string; - Metrics?: string[]; - } - - export interface EnableMetricsCollectionParams { - AutoScalingGroupName: string; - Granularity: string; - Metrics?: string[]; - } - - export interface EnterStandbyParams { - AutoScalingGroupName: string; - ShouldDecrementDesiredCapacity: boolean; - InstanceIds?: string[]; - } - - export interface ExecutePolicyParams { - PolicyName: string; - AutoScalingGroupName?: string; - HonorCooldown?: boolean; - MetricValue?: number; - BreachThreshold?: number; - } - - export interface ExitStandbyParams { - AutoScalingGroupName: string; - InstanceIds?: string[]; - } - - export interface PutLifecycleHookParams { - AutoScalingGroupName: string; - LifecycleHookName: string; - LifecycleTransition?: string; - RoleARN?: string; - NotificationTargetARN?: string; - NotificationMetadata?: string; - HeartbeatTimeout?: number; - DefaultResult?: string; - } - - export interface PutNotificationConfigurationParams { - AutoScalingGroupName: string; - NotificationTypes: string[]; - TopicARN: string; - } - - export interface PutScalingPolicyParams { - AutoScalingGroupName: string; - AdjustmentType: string; - PolicyName: string; - PolicyType?: string; - MinAdjustmentStep?: number; - MinAdjustmentMagnitude?: number; - ScalingAdjustment?: number; - Cooldown?: number; - MetricAggregationType?: string; - StepAdjustments?: StepAdjustment[]; - EstimatedInstanceWarmup: number; - } - - export interface PutScheduledUpdateGroupActionParams { - AutoScalingGroupName: string; - ScheduledActionName: string; - Time?: Date; - StartTime?: Date; - EndTime?: Date; - Recurrence?: string; - MinSize?: number; - MaxSize?: number; - DesiredCapacity?: number; - } - - export interface RecordLifecycleActionHeartbeatParams { - AutoScalingGroupName: string; - LifecycleHookName: string; - LifecycleActionToken?: string; - InstanceId?: string; - } - - export interface ResumeProcessesParams { - AutoScalingGroupName: string; - ScalingProcesses?: string[]; - } - - export interface SetDesiredCapacityParams { - AutoScalingGroupName: string; - DesiredCapacity: number; - HonorCooldown?: boolean; - } - - export interface SetInstanceHealthParams { - HealthStatus: string; - InstanceId: string; - ShouldRespectGracePeriod?: boolean; - } - - export interface SetInstanceProtectionParams { - AutoScalingGroupName: string; - InstanceIds: string[]; - ProtectedFromScaleIn: boolean; - } - - export interface SuspendProcessesParams { - AutoScalingGroupName: string; - ScalingProcesses?: string[]; - } - - export interface TerminateInstanceInAutoScalingGroupParams { - InstanceId: string; - ShouldDecrementDesiredCapacity: boolean; - } - - export interface UpdateAutoScalingGroupParams { - AutoScalingGroupName: string; - LaunchConfigurationName: string; - MinSize: number; - MaxSize: number; - DesiredCapacity: number; - DefaultCooldown: number; - AvailabilityZones: string[]; - HealthCheckType: string; - HealthCheckGracePeriod: number; - PlacementGroup: string; - VPCZoneIdentifier: string; - TerminationPolicies: string[]; - NewInstancesProtectedFromScaleIn?: boolean; - } + export interface AutoScalingOptions { + params?: any; + endpoint?: string; + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: Credentials; + credentials?: Credentials; + credentialProvider?: any; + region?: string; + maxRetries?: number; + maxRedirects?: number; + sslEnabled?: boolean; + paramValidation?: boolean; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + correctClockSkew?: boolean; + s3ForcePathStyle?: boolean; + s3BucketEndpoint?: boolean; + s3DisableBodySigning?: boolean; + retryDelayOptions?: RetryDelayOption; + httpOptions?: HttpOptions; + apiVersion?: string; + apiVersions?: { [serviceName: string]: string }; + logger?: Logger; + systemClockOffset?: number; + signatureVersion?: string; + signatureCache?: boolean; } + export interface AttachInstancesParams { + AutoScalingGroupName: string; + InstanceIds: string[]; + } + + export interface AttachLoadBalancersParams { + AutoScalingGroupName: string; + LoadBalancerNames: string[]; + } + + export interface AttachLoadBalancerTargetGroupsParams { + AutoScalingGroupName: string; + TargetGroupARNs: string[]; + } + + export interface CompleteLifecycleActionParams { + AutoScalingGroupName: string; + LifecycleActionResult: string; + LifecycleHookName: string; + lifecycleActionToken?: string; + InstanceId?: string; + } + + export interface CreateAutoScalingGroupParams { + AutoScalingGroupName: string; + MinSize: number; + MaxSize: number; + LaunchConfigurationName?: string; + InstanceId?: string; + DesiredCapacity?: number; + DefaultCooldown?: number; + AvailabilityZones?: string[]; + LoadBalancerNames?: string[]; + TargetGroupARNs?: string[]; + HealthCheckType?: string; + HealthCheckGracePeriod?: number; + PlacementGroup?: string; + VPCZoneIdentifier?: string; + TerminationPolicies?: string; + NewInstancesProtectedFromScaleIn?: boolean; + Tags?: Tags; + } + + export interface CreateLaunchConfigurationParams { + LaunchConfigurationName: string; + AssociatePublicIpAddress?: boolean; + ImageId?: string; + KeyName?: string; + SecurityGroups?: string[]; + ClassicLinkVPCId?: string; + ClassicLinkVPCSecurityGroups?: string[]; + UserData?: string; + InstanceId?: string; + InstanceType?: string; + KernelId?: string; + RamdiskId?: string; + BlockDeviceMappings?: BlockDeviceMapping[]; + InstanceMonitoring?: InstanceMonitoring; + SpotPrice?: string; + IamInstanceProfile?: string; + EbsOptimized?: boolean; + PlacementTenancy?: string; + } + + export interface CreateOrUpdateTagsParams { + Tags: Tags[]; + } + + export interface DeleteAutoScalingGroupParams { + AutoScalingGroupName: string; + ForceDelete?: boolean; + } + + export interface DeleteLaunchConfigurationParams { + LaunchConfigurationName: string; + } + + export interface DeleteLifecycleHookParams { + AutoScalingGroupName: string; + LifecycleHookName: string; + } + + export interface DeleteNotificationConfigurationParams { + AutoScalingGroupName: string; + TopicARN: string; + } + + export interface DeletePolicyParams { + PolicyName: string; + AutoScalingGroupName?: string; + } + + export interface DeleteScheduledActionParams { + AutoScalingGroupName: string; + ScheduledActionName: string; + } + + export interface DeleteTagsParams { + Tags: Tags[]; + } + + export interface DescribeAutoScalingGroupsParams { + AutoScalingGroupName?: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeAutoScalingInstancesParams { + InstanceIds?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeLaunchConfigurationsParams { + LaunchConfigurationNames?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeLifecycleHooksParams { + AutoScalingGroupName: string; + LifecycleHookNames?: string[]; + } + + export interface DescribeLoadBalancersParams { + AutoScalingGroupName: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeLoadBalancerTargetGroupsParams { + AutoScalingGroupName: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeNotificationConfigurationsParams { + AutoScalingGroupName?: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribePoliciesParams { + AutoScalingGroupName?: string; + PolicyNames?: string[]; + PolicyTypes?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeScalingActivitiesParams { + AutoScalingGroupName?: string; + ActivityIds?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeScheduledActionsParams { + AutoScalingGroupName?: string; + ScheduledActionNames?: string[]; + StartTime?: Date; + EndTime?: Date; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeTagsParams { + Filters?: Filter[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DetachInstancesParams { + AutoScalingGroupName: string; + ShouldDecrementDesiredCapacity: boolean; + InstanceIds?: string[]; + } + + export interface DetachLoadBalancersParams { + AutoScalingGroupName: string; + LoadBalancerNames: string; + } + + export interface DetachLoadBalancerTargetGroupsParams { + AutoScalingGroupName: string; + TargetGroupARNs: string[]; + } + + export interface DisableMetricsCollectionParams { + AutoScalingGroupName: string; + Metrics?: string[]; + } + + export interface EnableMetricsCollectionParams { + AutoScalingGroupName: string; + Granularity: string; + Metrics?: string[]; + } + + export interface EnterStandbyParams { + AutoScalingGroupName: string; + ShouldDecrementDesiredCapacity: boolean; + InstanceIds?: string[]; + } + + export interface ExecutePolicyParams { + PolicyName: string; + AutoScalingGroupName?: string; + HonorCooldown?: boolean; + MetricValue?: number; + BreachThreshold?: number; + } + + export interface ExitStandbyParams { + AutoScalingGroupName: string; + InstanceIds?: string[]; + } + + export interface PutLifecycleHookParams { + AutoScalingGroupName: string; + LifecycleHookName: string; + LifecycleTransition?: string; + RoleARN?: string; + NotificationTargetARN?: string; + NotificationMetadata?: string; + HeartbeatTimeout?: number; + DefaultResult?: string; + } + + export interface PutNotificationConfigurationParams { + AutoScalingGroupName: string; + NotificationTypes: string[]; + TopicARN: string; + } + + export interface PutScalingPolicyParams { + AutoScalingGroupName: string; + AdjustmentType: string; + PolicyName: string; + PolicyType?: string; + MinAdjustmentStep?: number; + MinAdjustmentMagnitude?: number; + ScalingAdjustment?: number; + Cooldown?: number; + MetricAggregationType?: string; + StepAdjustments?: StepAdjustment[]; + EstimatedInstanceWarmup: number; + } + + export interface PutScheduledUpdateGroupActionParams { + AutoScalingGroupName: string; + ScheduledActionName: string; + Time?: Date; + StartTime?: Date; + EndTime?: Date; + Recurrence?: string; + MinSize?: number; + MaxSize?: number; + DesiredCapacity?: number; + } + + export interface RecordLifecycleActionHeartbeatParams { + AutoScalingGroupName: string; + LifecycleHookName: string; + LifecycleActionToken?: string; + InstanceId?: string; + } + + export interface ResumeProcessesParams { + AutoScalingGroupName: string; + ScalingProcesses?: string[]; + } + + export interface SetDesiredCapacityParams { + AutoScalingGroupName: string; + DesiredCapacity: number; + HonorCooldown?: boolean; + } + + export interface SetInstanceHealthParams { + HealthStatus: string; + InstanceId: string; + ShouldRespectGracePeriod?: boolean; + } + + export interface SetInstanceProtectionParams { + AutoScalingGroupName: string; + InstanceIds: string[]; + ProtectedFromScaleIn: boolean; + } + + export interface SuspendProcessesParams { + AutoScalingGroupName: string; + ScalingProcesses?: string[]; + } + + export interface TerminateInstanceInAutoScalingGroupParams { + InstanceId: string; + ShouldDecrementDesiredCapacity: boolean; + } + + export interface UpdateAutoScalingGroupParams { + AutoScalingGroupName: string; + LaunchConfigurationName: string; + MinSize: number; + MaxSize: number; + DesiredCapacity: number; + DefaultCooldown: number; + AvailabilityZones: string[]; + HealthCheckType: string; + HealthCheckGracePeriod: number; + PlacementGroup: string; + VPCZoneIdentifier: string; + TerminationPolicies: string[]; + NewInstancesProtectedFromScaleIn?: boolean; + } + } + export module SQS { From c3d42974315ac7f01a56ce10b57e7b71affbe8e9 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Sat, 27 Aug 2016 00:43:42 +0800 Subject: [PATCH 146/844] Add module "process" for Node v4 --- node/node-4.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/node/node-4.d.ts b/node/node-4.d.ts index 848b0536d0..d6fb33f750 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -2402,3 +2402,7 @@ declare module "constants" { export var X_OK: number; export var UV_UDP_REUSEADDR: number; } + +declare module "process" { + export = process; +} From 51c51f03549a63f8791865bf26480947e22f4902 Mon Sep 17 00:00:00 2001 From: Simon Date: Fri, 26 Aug 2016 16:49:28 -0400 Subject: [PATCH 147/844] adds __v property to document --- mongoose/mongoose-tests.ts | 1 + mongoose/mongoose.d.ts | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 51959b9e41..5feb08b446 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1081,6 +1081,7 @@ var MongoModel = mongoose.model('MongoModel', new mongoose.Schema({ }), 'myCollection', true); MongoModel.find({}).$where('indexOf("val") !== -1').exec(function (err, docs) { docs[0].save(); + docs[0].__v; }); MongoModel.findById(999, function (err, doc) { doc.increment(); diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 89fc9073a4..2d0046ea8c 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2332,6 +2332,12 @@ declare module "mongoose" { * @param fn optional callback */ save(fn?: (err: any, product: this, numAffected: number) => void): Promise; + + /** + * Version using default version key. See http://mongoosejs.com/docs/guide.html#versionKey + * If you're using another key, you will have to access it using []: doc[_myVersionKey] + */ + __v?: number; } interface ModelProperties { From 93c2c8d50b159c99b8c55bf2a3204ddd6e63e59b Mon Sep 17 00:00:00 2001 From: JC Franco Date: Fri, 26 Aug 2016 14:08:17 -0700 Subject: [PATCH 148/844] [maquette] Add Projector#detach. --- maquette/maquette.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/maquette/maquette.d.ts b/maquette/maquette.d.ts index 7ad5081ed0..b1ee5bc9c7 100644 --- a/maquette/maquette.d.ts +++ b/maquette/maquette.d.ts @@ -325,6 +325,14 @@ declare namespace maquette { * @param {function} renderMaquetteFunction - Function with zero arguments that returns a {@link VNode} tree. */ append(parentNode: Element, renderMaquetteFunction: () => VNode): void; + /** + * Stops running the `renderMaquetteFunction` to update the DOM. The `renderMaquetteFunction` must have been + * registered using [[append]], [[merge]], [[insertBefore]] or [[replace]]. + * + * @returns The [[Projection]] which was created using this `renderMaquetteFunction`. + * The [[Projection]] contains a reference to the DOM Node that was rendered. + */ + detach(renderMaquetteFunction: () => VNode): Projection; /** * Scans the document for ` + * + * @example + * AMD + * // main.js + * require.config({ + * paths: { + * braintreeClient: 'https://js.braintreegateway.com/web/3.0.2/js/client.min' + * } + * }); + * + * require(['braintreeClient'], function (braintreeClient) { + * braintreeClient.create(...); + * }); + */ +interface BraintreeStatic { + /** @type {module:braintree-web/client} */ + client: BraintreeWeb.Client; + + /** @type {module:braintree-web/paypal} */ + paypal: BraintreeWeb.PayPal; + + /** @type {module:braintree-web/hosted-fields} */ + hostedFields: BraintreeWeb.HostedFields; + + /** @type {module:braintree-web/three-d-secure} */ + threeDSecure: BraintreeWeb.ThreeDSecure; + + /** @type {module:braintree-web/data-collector} */ + dataCollector: BraintreeWeb.DataCollector; + + /** @type {module:braintree-web/american-express} */ + americanExpress: BraintreeWeb.AmericanExpress; + + /** @type {module:braintree-web/unionpay} */ + unionpay: BraintreeWeb.UnionPay; + + /** @type {module:braintree-web/apple-pay} */ + applePay: BraintreeWeb.ApplePay; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; +} + +declare var braintree: BraintreeStatic; \ No newline at end of file From b6b192d3ea2bb488eceee72338190c1e7617e139 Mon Sep 17 00:00:00 2001 From: Niklas Mollenhauer Date: Fri, 9 Sep 2016 16:26:34 +0200 Subject: [PATCH 436/844] Add humps definitions (#11127) --- humps/humps-tests.ts | 71 ++++++++++++++++++++++++++++++++++++++++++++ humps/humps.d.ts | 39 ++++++++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 humps/humps-tests.ts create mode 100644 humps/humps.d.ts diff --git a/humps/humps-tests.ts b/humps/humps-tests.ts new file mode 100644 index 0000000000..66017b065c --- /dev/null +++ b/humps/humps-tests.ts @@ -0,0 +1,71 @@ +/// + +// Tests evaluated from: +// https://github.com/domchristie/humps/blob/master/README.md + +import * as humps from "humps"; + +let someObject = { attr_one: 'foo', attr_two: 'bar' }; +let someArray = [{ attr_one: 'foo' }, { attr_one: 'bar' }] + +let someOptions: humps.HumpsOptions = { + separator: '-' +}; +let someOptions2: humps.HumpsOptions = { + split: /^[A-Z0-9_]+$/ +}; +let someOptions3: humps.HumpsOptions = { + separator: '-', + process: function (key: string, convert: humps.HumpsProcessorParameter, options: humps.HumpsOptions) { + return /^[A-Z0-9_]+$/.test(key) ? key : convert(key, options); + } +}; + + +humps.camelize('hello_world') + +humps.decamelize('fooBar') +humps.decamelize('fooBarBaz', someOptions) + +humps.camelizeKeys(someObject); + +humps.camelizeKeys(someArray); + +humps.camelizeKeys(someObject, function (key, convert) { + return /^[A-Z0-9_]+$/.test(key) ? key : convert(key); +}); + +humps.decamelizeKeys(someObject, function (key, convert, options) { + return /^[A-Z0-9_]+$/.test(key) ? key : convert(key, options); +}); + + +humps.camelize('hello_world-foo bar'); + +humps.pascalize('hello_world-foo bar'); + +humps.decamelize('helloWorldFooBar'); +humps.decamelize('helloWorldFooBar', someOptions); +humps.decamelize('helloWorld1', { split: /(?=[A-Z0-9])/ }) + +humps.depascalize('helloWorldFooBar'); + +humps.camelizeKeys(someObject); +humps.pascalizeKeys(someObject); +humps.decamelizeKeys(someObject); +humps.depascalizeKeys(someObject); + +humps.camelizeKeys(someObject, someOptions); +humps.pascalizeKeys(someObject, someOptions); +humps.decamelizeKeys(someObject, someOptions); +humps.depascalizeKeys(someObject, someOptions); + +humps.camelizeKeys(someObject, someOptions2); +humps.pascalizeKeys(someObject, someOptions2); +humps.decamelizeKeys(someObject, someOptions2); +humps.depascalizeKeys(someObject, someOptions2); + +humps.camelizeKeys(someObject, someOptions3); +humps.pascalizeKeys(someObject, someOptions3); +humps.decamelizeKeys(someObject, someOptions3); +humps.depascalizeKeys(someObject, someOptions3); diff --git a/humps/humps.d.ts b/humps/humps.d.ts new file mode 100644 index 0000000000..87f3bbd991 --- /dev/null +++ b/humps/humps.d.ts @@ -0,0 +1,39 @@ +// Type definitions for humps v1.1.0 +// Project: https://github.com/domchristie/humps +// Definitions by: Niklas Mollenhauer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace humps { + + function camelize(value: string): string; + function pascalize(value: string): string; + function decamelize(value: string, optionsOrProcessor?: OptionOrProcessor): string; + function depascalize(value: string, optionsOrProcessor?: OptionOrProcessor): string; + + function camelizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + function pascalizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + function decamelizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + function depascalizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + + function camelizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + function pascalizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + function decamelizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + function depascalizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + + interface HumpsOptions { + separator?: string; + split?: RegExp; + process?: HumpsProcessor; + } + interface HumpsProcessor { + (key: string, convert: HumpsProcessorParameter, options?: HumpsOptions): string; + } + interface HumpsProcessorParameter { + (key: string, options?: HumpsOptions): string; + } + type OptionOrProcessor = HumpsOptions | HumpsProcessor; +} + +declare module "humps" { + export = humps; +} From 3d232e8f3017bdde5b263810f722b2af5a4cc078 Mon Sep 17 00:00:00 2001 From: Leonardo Salgueiro Date: Fri, 9 Sep 2016 07:31:54 -0700 Subject: [PATCH 437/844] fixing a typo in cache-manager/cache-manager.d.ts (#11129) --- cache-manager/cache-manager.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cache-manager/cache-manager.d.ts b/cache-manager/cache-manager.d.ts index 9570857f01..de6cf867a7 100644 --- a/cache-manager/cache-manager.d.ts +++ b/cache-manager/cache-manager.d.ts @@ -28,7 +28,7 @@ declare module 'cache-manager' { module cacheManager { - function caching(ICongig: StoreConfig): Cache; + function caching(IConfig: StoreConfig): Cache; function multiCaching(Caches: Cache[]): Cache; } From fc1b3e11dfe8e1cae861e8a71ea1a5f18c27446f Mon Sep 17 00:00:00 2001 From: TonyYang Date: Fri, 9 Sep 2016 22:33:18 +0800 Subject: [PATCH 438/844] [node] imported and global process are same (#11092) * imported and global process are same * imported and global process are same --- node/node-4-tests.ts | 17 ++++++++++++++++- node/node-tests.ts | 11 ++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 348723ea6e..af139829c7 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -872,6 +872,22 @@ namespace errors_tests { } } +/////////////////////////////////////////////////////////// +/// Process Tests : https://nodejs.org/api/process.html /// +/////////////////////////////////////////////////////////// + +import * as p from "process"; +namespace process_tests{ + { + var eventEmitter: events.EventEmitter; + eventEmitter = process; // Test that process implements EventEmitter... + + var _p: NodeJS.Process = process; + _p = p; + assert(p === process); + } +} + /////////////////////////////////////////////////////////// /// Console Tests : https://nodejs.org/api/console.html /// /////////////////////////////////////////////////////////// @@ -882,4 +898,3 @@ namespace console_tests{ assert(c === console); } } - diff --git a/node/node-tests.ts b/node/node-tests.ts index 05d0b177a2..1af627e1e1 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -1078,10 +1078,19 @@ namespace errors_tests { } } +/////////////////////////////////////////////////////////// +/// Process Tests : https://nodejs.org/api/process.html /// +/////////////////////////////////////////////////////////// + +import * as p from "process"; namespace process_tests{ { var eventEmitter: events.EventEmitter; - eventEmitter = process; // Test that process implements EventEmitter... + eventEmitter = process; // Test that process implements EventEmitter... + + var _p: NodeJS.Process = process; + _p = p; + assert(p === process); } } From f665c7f52391c1861e3f31bc99f535e37550ee17 Mon Sep 17 00:00:00 2001 From: Alex Staroselsky Date: Fri, 9 Sep 2016 09:40:00 -0500 Subject: [PATCH 439/844] =?UTF-8?q?Added=20toast=20class=20property=20to?= =?UTF-8?q?=20toast=20options/config=20object=20per=20commit=20=E2=80=A6?= =?UTF-8?q?=20(#11132)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Added toast class property to toast options/config object per commit f72c7816. Added id property to panel config per commit d230aec. * Added onClose() callback to sidenav object per commit 1f01d264. --- angular-material/angular-material-tests.ts | 15 +++++++++++++++ angular-material/angular-material.d.ts | 3 +++ 2 files changed, 18 insertions(+) diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts index 4464c599e3..c3ebcbaf99 100644 --- a/angular-material/angular-material-tests.ts +++ b/angular-material/angular-material-tests.ts @@ -127,15 +127,30 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia instance.isOpen(); instance.isLockedOpen(); }); + + $scope['onClose'] = $mdSidenav(componentId).onClose(() => {}); }); myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => { $scope['openToast'] = () => $mdToast.show($mdToast.simple().textContent('Hello!')); + + $scope['customToast'] = () => { + var options = { + hideDelay: 3000, + position: 'top right', + controller : 'ToastCtrl', + templateUrl : 'toast-template.html', + toastClass: 'my-class' + }; + + $mdToast.show(options); + } }); myApp.controller('PanelController', ($scope: ng.IScope, $mdPanel: ng.material.IPanelService) => { $scope['createPanel'] = () => { var config = { + id: 'myPanel', template: '

    Hello!

    ', hasBackdrop: true, disableParentScroll: true, diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index f408c602f3..66852586da 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -132,6 +132,7 @@ declare namespace angular.material { close(): angular.IPromise; isOpen(): boolean; isLockedOpen(): boolean; + onClose(onClose: Function): void; } interface ISidenavService { @@ -162,6 +163,7 @@ declare namespace angular.material { preserveScope?: boolean; // default: false hideDelay?: number; // default (ms): 3000 position?: string; // any combination of 'bottom'/'left'/'top'/'right'/'fit'; default: 'bottom left' + toastClass?: string; controller?: string|Function; locals?: {[index: string]: any}; bindToController?: boolean; // default: false @@ -291,6 +293,7 @@ declare namespace angular.material { } interface IPanelConfig { + id?: string; template?: string; templateUrl?: string; controller?: string|Function; From 951b75c3fbbe92d07866b728d4074ac0d3a284bd Mon Sep 17 00:00:00 2001 From: Maksym Butsykin Date: Fri, 9 Sep 2016 17:43:31 +0300 Subject: [PATCH 440/844] Change type definition for angular-es@1.0.0 (#11141) --- angular-es/angular-es.d.ts | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/angular-es/angular-es.d.ts b/angular-es/angular-es.d.ts index 10979ae15c..0972b42da0 100644 --- a/angular-es/angular-es.d.ts +++ b/angular-es/angular-es.d.ts @@ -45,12 +45,12 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Component: (component: iComponent) => ngESDecorator; + function Component(component: iComponent): ngESDecorator; /** * Register config block */ - var Config: () => ngESDecorator; + function Config(): ngESDecorator; /** * Register constant @@ -59,7 +59,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Constant: (name: string) => ngESDecorator; + function Constant(name: string): ngESDecorator; /** * Register controller @@ -68,7 +68,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Controller: (name: string) => ngESDecorator; + function Controller(name: string): ngESDecorator; /** * Register decorator @@ -77,7 +77,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Decorator: (name: string) => ngESDecorator; + function Decorator(name: string): ngESDecorator; /** * Register directive @@ -86,7 +86,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Directive: (name: string) => ngESDecorator; + function Directive(name: string): ngESDecorator; /** * Register factory @@ -95,7 +95,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Factory: (name: string) => ngESDecorator; + function Factory(name: string): ngESDecorator; /** * Register filter @@ -104,7 +104,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Filter: (name: string) => ngESDecorator; + function Filter(name: string): ngESDecorator; /** * Add $inject property to target @@ -113,7 +113,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Inject: (...dependencies: Array) => ngESDecorator; + function Inject(...dependencies: Array): ngESDecorator; /** * Inject dependencies as properties to target @@ -122,7 +122,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var InjectAsProperty: (...dependencies: Array) => ngESDecorator; + function InjectAsProperty(...dependencies: Array): ngESDecorator; /** * Attach target to the specified module @@ -131,7 +131,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Module: (name: string) => ngESDecorator; + function Module(name: string): ngESDecorator; /** * Register provider @@ -140,14 +140,14 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Provider: (name: string) => ngESDecorator; + function Provider(name: string): ngESDecorator; /** * Register run block * * @returns {ngESDecorator} - decorated class */ - var Run: () => ngESDecorator; + function Run(): ngESDecorator; /** * Register service @@ -156,7 +156,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Service: (name: string) => ngESDecorator; + function Service(name: string): ngESDecorator; /** * Register value @@ -165,7 +165,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var Value: (name: string) => ngESDecorator; + function Value(name: string): ngESDecorator; export { Component, From c49a53466c6f7cd5a5763f66d2452545082ac4ca Mon Sep 17 00:00:00 2001 From: hriss95 Date: Fri, 9 Sep 2016 15:45:18 +0100 Subject: [PATCH 441/844] Node.d.ts: Update definitions for module "dgram" (#11143) --- node/node.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index f2a05aecc8..ff9612e9bb 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1423,14 +1423,14 @@ declare module "dgram" { } interface SocketOptions { - type: string; + type: "udp4" | "udp6"; reuseAddr?: boolean; } export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - interface Socket extends events.EventEmitter { + export interface Socket extends events.EventEmitter { send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error, bytes: number) => void): void; send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; bind(port?: number, address?: string, callback?: () => void): void; From 3467f1cd38219068ae1c1cc374a2d8fdc920cc95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20S=C3=A1nchez?= Date: Fri, 9 Sep 2016 08:49:08 -0600 Subject: [PATCH 442/844] Added typings for libxslt (#11094) --- libxslt/libxslt-tests.ts | 102 +++++++++++++++++++++++++++++++++++++++ libxslt/libxslt.d.ts | 61 +++++++++++++++++++++++ 2 files changed, 163 insertions(+) create mode 100644 libxslt/libxslt-tests.ts create mode 100644 libxslt/libxslt.d.ts diff --git a/libxslt/libxslt-tests.ts b/libxslt/libxslt-tests.ts new file mode 100644 index 0000000000..544269b11e --- /dev/null +++ b/libxslt/libxslt-tests.ts @@ -0,0 +1,102 @@ +/// +/// + +import * as libxslt from 'libxslt'; +import * as libxmljs from 'libxmljs'; + +const document: libxmljs.XMLDocument = libxslt.libxmljs.parseXmlString(''); + +let stylesheet: libxslt.Stylesheet; + +stylesheet = libxslt.parse(''); + +stylesheet = libxslt.parse(document); + +libxslt.parse('', (err, result) => { + if (err == null) { + stylesheet = result; + } +}); + +libxslt.parse(document, (err, result) => { + if (err == null) { + stylesheet = result; + } +}); + +libxslt.parseFile('/path/to/file', (err, result) => { + if (err == null) { + stylesheet = result; + } +}); + +let applyOptions: libxslt.ApplyOptions = {}; + +applyOptions = { + outputFormat: 'string', + noWrapParams: true +}; + +let transformedString: string; + +let transformedDocument: libxmljs.XMLDocument; + +transformedString = stylesheet.apply(''); + +transformedString = stylesheet.apply('', {}); + +let applyResult = stylesheet.apply('', {}, applyOptions); + +if (typeof applyResult === 'string') { + transformedString = applyResult; +} else { + transformedDocument = applyResult; +} + +stylesheet.apply('', {}, applyOptions, (err, result) => { + if (err != null) { + return; + } + + if (typeof result === 'string') { + transformedString = result; + } else { + transformedDocument = result; + } +}); + +transformedDocument = stylesheet.apply(document); + +transformedDocument = stylesheet.apply(document, {}); + +applyResult = stylesheet.apply(document, {}, applyOptions); + +if (typeof applyResult === 'string') { + transformedString = applyResult; +} else { + transformedDocument = applyResult; +} + +stylesheet.apply(document, {}, applyOptions, (err, result) => { + if (err != null) { + return; + } + + if (typeof result === 'string') { + transformedString = result; + } else { + transformedDocument = result; + } +}); + +stylesheet.applyToFile('/path/to/file', {}, applyOptions, (err, result) => { + if (err == null) { + transformedString = result; + } +}); + +stylesheet.applyToFile('/path/to/file', (err, result) => { + if (err == null) { + transformedString = result; + } +}); diff --git a/libxslt/libxslt.d.ts b/libxslt/libxslt.d.ts new file mode 100644 index 0000000000..0cfd4e1bcd --- /dev/null +++ b/libxslt/libxslt.d.ts @@ -0,0 +1,61 @@ +// Type definitions for node-libxslt +// Project: https://github.com/albanm/node-libxslt +// Definitions by: Alejandro Sánchez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'libxslt' { + import * as xmljs from 'libxmljs'; + + export const libxmljs: typeof xmljs; + + type OutputFormat = 'document' | 'string'; + + export interface ApplyOptions { + outputFormat?: OutputFormat; + noWrapParams?: boolean; + } + + type ApplyResult = string | xmljs.XMLDocument; + + type ApplyCallback = (err: Error, result: ApplyResult) => void; + + type ApplyStringCallback = (err: Error, result: string) => void; + + type ApplyDocumentCallback = (err: Error, result: xmljs.XMLDocument) => void; + + export interface Stylesheet { + apply(source: string, params?: Object): string; + + apply(source: string, params: Object, options: ApplyOptions): ApplyResult; + + apply(source: string, params: Object, options: ApplyOptions, callback: ApplyCallback): void; + + apply(source: string, callback: ApplyStringCallback): void; + + apply(source: xmljs.XMLDocument, params?: Object): xmljs.XMLDocument; + + apply(source: xmljs.XMLDocument, params: Object, options: ApplyOptions): ApplyResult; + + apply(source: xmljs.XMLDocument, params: Object, options: ApplyOptions, callback: ApplyCallback): void; + + apply(source: xmljs.XMLDocument, callback: ApplyDocumentCallback): void; + + applyToFile(sourcePath: string, params: Object, options: ApplyOptions, callback: ApplyStringCallback): void; + + applyToFile(sourcePath: string, callback: ApplyStringCallback): void; + } + + type ParseCallback = (err: Error, stylesheet: Stylesheet) => void; + + export function parse(source: string): Stylesheet; + + export function parse(source: string, callback: ParseCallback): void; + + export function parse(source: xmljs.XMLDocument): Stylesheet; + + export function parse(source: xmljs.XMLDocument, callback: ParseCallback): void; + + export function parseFile(sourcePath: string, callback: ParseCallback): void; +} From 1d50912b2bc5df5de9a4393b8e39f7ba35b21550 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Fri, 9 Sep 2016 22:52:36 +0800 Subject: [PATCH 443/844] [node] Correct constants module for node v6 (#11140) * Correct constants module * Add tests for constants * Typo namespace * Recovery constants module and add two stuffs --- node/node-tests.ts | 152 +++++++++++++++++++++++++++++++++++++++++++++ node/node.d.ts | 4 +- 2 files changed, 155 insertions(+), 1 deletion(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index 1af627e1e1..0ffc145025 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -1104,3 +1104,155 @@ namespace console_tests{ assert(c === console); } } + +/***************************************************************************** + * * + * The following tests are the modules not mentioned in document but existed * + * * + *****************************************************************************/ + +/////////////////////////////////////////////////////////// +/// Constants Tests /// +/////////////////////////////////////////////////////////// + +import * as constants from 'constants'; +namespace constants_tests { + var str: string; + var num: number; + num = constants.SIGHUP + num = constants.SIGINT + num = constants.SIGQUIT + num = constants.SIGILL + num = constants.SIGTRAP + num = constants.SIGABRT + num = constants.SIGIOT + num = constants.SIGBUS + num = constants.SIGFPE + num = constants.SIGKILL + num = constants.SIGUSR1 + num = constants.SIGSEGV + num = constants.SIGUSR2 + num = constants.SIGPIPE + num = constants.SIGALRM + num = constants.SIGTERM + num = constants.SIGCHLD + num = constants.SIGSTKFLT + num = constants.SIGCONT + num = constants.SIGSTOP + num = constants.SIGTSTP + num = constants.SIGTTIN + num = constants.SIGTTOU + num = constants.SIGURG + num = constants.SIGXCPU + num = constants.SIGXFSZ + num = constants.SIGVTALRM + num = constants.SIGPROF + num = constants.SIGWINCH + num = constants.SIGIO + num = constants.SIGPOLL + num = constants.SIGPWR + num = constants.SIGSYS + num = constants.SIGUNUSED + num = constants.O_RDONLY + num = constants.O_WRONLY + num = constants.O_RDWR + num = constants.S_IFMT + num = constants.S_IFREG + num = constants.S_IFDIR + num = constants.S_IFCHR + num = constants.S_IFBLK + num = constants.S_IFIFO + num = constants.S_IFLNK + num = constants.S_IFSOCK + num = constants.O_CREAT + num = constants.O_EXCL + num = constants.O_NOCTTY + num = constants.O_TRUNC + num = constants.O_APPEND + num = constants.O_DIRECTORY + num = constants.O_NOATIME + num = constants.O_NOFOLLOW + num = constants.O_SYNC + num = constants.O_DIRECT + num = constants.O_NONBLOCK + num = constants.S_IRWXU + num = constants.S_IRUSR + num = constants.S_IWUSR + num = constants.S_IXUSR + num = constants.S_IRWXG + num = constants.S_IRGRP + num = constants.S_IWGRP + num = constants.S_IXGRP + num = constants.S_IRWXO + num = constants.S_IROTH + num = constants.S_IWOTH + num = constants.S_IXOTH + num = constants.F_OK + num = constants.R_OK + num = constants.W_OK + num = constants.X_OK + num = constants.SSL_OP_ALL + num = constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION + num = constants.SSL_OP_CIPHER_SERVER_PREFERENCE + num = constants.SSL_OP_CISCO_ANYCONNECT + num = constants.SSL_OP_COOKIE_EXCHANGE + num = constants.SSL_OP_CRYPTOPRO_TLSEXT_BUG + num = constants.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS + num = constants.SSL_OP_EPHEMERAL_RSA + num = constants.SSL_OP_LEGACY_SERVER_CONNECT + num = constants.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER + num = constants.SSL_OP_MICROSOFT_SESS_ID_BUG + num = constants.SSL_OP_MSIE_SSLV2_RSA_PADDING + num = constants.SSL_OP_NETSCAPE_CA_DN_BUG + num = constants.SSL_OP_NETSCAPE_CHALLENGE_BUG + num = constants.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG + num = constants.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG + num = constants.SSL_OP_NO_COMPRESSION + num = constants.SSL_OP_NO_QUERY_MTU + num = constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION + num = constants.SSL_OP_NO_SSLv2 + num = constants.SSL_OP_NO_SSLv3 + num = constants.SSL_OP_NO_TICKET + num = constants.SSL_OP_NO_TLSv1 + num = constants.SSL_OP_NO_TLSv1_1 + num = constants.SSL_OP_NO_TLSv1_2 + num = constants.SSL_OP_PKCS1_CHECK_1 + num = constants.SSL_OP_PKCS1_CHECK_2 + num = constants.SSL_OP_SINGLE_DH_USE + num = constants.SSL_OP_SINGLE_ECDH_USE + num = constants.SSL_OP_SSLEAY_080_CLIENT_DH_BUG + num = constants.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG + num = constants.SSL_OP_TLS_BLOCK_PADDING_BUG + num = constants.SSL_OP_TLS_D5_BUG + num = constants.SSL_OP_TLS_ROLLBACK_BUG + num = constants.ENGINE_METHOD_RSA + num = constants.ENGINE_METHOD_DSA + num = constants.ENGINE_METHOD_DH + num = constants.ENGINE_METHOD_RAND + num = constants.ENGINE_METHOD_ECDH + num = constants.ENGINE_METHOD_ECDSA + num = constants.ENGINE_METHOD_CIPHERS + num = constants.ENGINE_METHOD_DIGESTS + num = constants.ENGINE_METHOD_STORE + num = constants.ENGINE_METHOD_PKEY_METHS + num = constants.ENGINE_METHOD_PKEY_ASN1_METHS + num = constants.ENGINE_METHOD_ALL + num = constants.ENGINE_METHOD_NONE + num = constants.DH_CHECK_P_NOT_SAFE_PRIME + num = constants.DH_CHECK_P_NOT_PRIME + num = constants.DH_UNABLE_TO_CHECK_GENERATOR + num = constants.DH_NOT_SUITABLE_GENERATOR + num = constants.NPN_ENABLED + num = constants.ALPN_ENABLED + num = constants.RSA_PKCS1_PADDING + num = constants.RSA_SSLV23_PADDING + num = constants.RSA_NO_PADDING + num = constants.RSA_PKCS1_OAEP_PADDING + num = constants.RSA_X931_PADDING + num = constants.RSA_PKCS1_PSS_PADDING + num = constants.POINT_CONVERSION_COMPRESSED + num = constants.POINT_CONVERSION_UNCOMPRESSED + num = constants.POINT_CONVERSION_HYBRID + str = constants.defaultCoreCipherList + str = constants.defaultCipherList +} diff --git a/node/node.d.ts b/node/node.d.ts index ff9612e9bb..bf5da3f226 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2764,6 +2764,8 @@ declare module "constants" { export var SIGUNUSED: number; export var defaultCoreCipherList: string; export var defaultCipherList: string; + export var ENGINE_METHOD_RSA: number; + export var ALPN_ENABLED: number; } declare module "process" { @@ -2794,4 +2796,4 @@ declare module "timers" { declare module "console" { export = console; -} \ No newline at end of file +} From 42ffdfc9371c6e178d104696f089299d5ed48aa2 Mon Sep 17 00:00:00 2001 From: Travis Hill Date: Fri, 9 Sep 2016 10:55:14 -0400 Subject: [PATCH 444/844] Added definitions for Validate.js (#10988) * Added definitions for Validate.js This does not include tests or full functionality definitions. It is intended to be a starting point for this library's definitions. Others can improve it. * Added required comments * Added test file for Validate.js --- validate.js/validate.js-tests.ts | 184 +++++++++++++++++++++++++++++++ validate.js/validate.js.d.ts | 109 ++++++++++++++++++ 2 files changed, 293 insertions(+) create mode 100644 validate.js/validate.js-tests.ts create mode 100644 validate.js/validate.js.d.ts diff --git a/validate.js/validate.js-tests.ts b/validate.js/validate.js-tests.ts new file mode 100644 index 0000000000..c9294de25d --- /dev/null +++ b/validate.js/validate.js-tests.ts @@ -0,0 +1,184 @@ +/// +import Validator = ValidateJS.Validator; +import Field = ValidateJS.Field; +import Constraints = ValidateJS.Constraints; + +let validator: Validator; +validator = {}; +validator = {message: 'test'}; +validator = {message: (value: any, attribute: any, validatorOptions: any, attributes: any, globalOptions: any) => 'test'}; + +let date: Validator.Date; +date = {}; +date = { + earliest: 'a', + latest: 'b', + notValid: 'c', + tooEarly: 'd', + tooLate: 'e', + message: 'test', +}; + +let dateTime: Validator.DateTime; +dateTime = {}; +dateTime = { + dateOnly: true, + earliest: 'a', + latest: 'b', + notValid: 'c', + tooEarly: 'd', + tooLate: 'e', + message: 'test', +}; + +let email: Validator.Email; +email = {}; +email = {message: 'test'}; + +let equality: Validator.Equality; +equality = {}; +equality = { + attribute: 'a', + comparator: (v1: any, v2: any) => true, + message: 'test', +}; + +let exclusion: Validator.Exclusion; +exclusion = { + within: ['a', 'b'], + message: 'test', +}; +exclusion = { + within: {a: 'b', c: 'd'}, +}; + +let format: Validator.Format; +format = { + pattern: 'a', + message: 'test', +}; +format = { + pattern: /a/g, +}; +format = { + pattern: new RegExp('a'), +}; + +let inclusion: Validator.Inclusion; +inclusion = { + within: ['a', 'b'], + message: 'test', +}; +inclusion = { + within: {a: 'b', c: 'd'}, +}; + +let _length: Validator.Length; +_length = {}; +_length = { + is: 1, + notValid: 'a', + wrongLength: 'b', + message: 'test', + tokenizer: (value: any[]) => [1, 2], +}; +_length = { + minimum: 2, + maximum: 4, + tooShort: 'a', + tooLong: 'b', + tokenizer: (value: string) => 'test', +}; + +let numericality: Validator.Numericality; +numericality = {}; +numericality = { + onlyInteger: true, + strict: true, + equalTo: 8, + divisibleBy: 4, + even: true, + notValid: 'a', + notInteger: 'b', + notEqualTo: 'c', + notDivisibleBy: 'd', + notEven: 'e', + message: 'test', +}; +numericality = { + greaterThan: 4, + lessThan: 10, + odd: true, + notGreaterThan: 'a', + notLessThan: 'b', + notOdd: 'c', +}; +numericality = { + greaterThanOrEqualTo: 4, + lessThanOrEqualTo: 7, + notGreaterThanOrEqualTo: 'a', + notLessThanOrEqualTo: 'b', +}; + +let presence: Validator.Presence; +presence = {}; +presence = {message: 'test'}; + +let url: Validator.Url; +url = {}; +url = { + schemes: ['a', /b/g, new RegExp('c')], + allowLocal: true, + message: 'test', +}; + +let field: Field; +field = {}; +field = { + date: {earliest: 'a'}, + datetime: {dateOnly: true}, + email: {message: 'test'}, + equality: {attribute: 'b'}, + exclusion: {within: ['c']}, + format: {pattern: 'd'}, + inclusion: {within: ['e']}, + length: {is: 4}, + numericality: {onlyInteger: true}, + presence: {message: 'test2'}, + url: {schemes: ['f']}, +}; +field = { + date: true, + datetime: true, + email: true, + equality: 'a', + exclusion: ['b'], + format: 'c', + inclusion: ['d'], + numericality: true, + presence: true, + url: true, +}; +field = { + format: /a/g, +}; +field = { + date: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({earliest: 'a'}), + datetime: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({dateOnly: true}), + email: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({message: 'test'}), + equality: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({attribute: 'b'}), + exclusion: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({within: ['c']}), + format: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({pattern: 'd'}), + inclusion: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({within: ['e']}), + length: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({is: 4}), + numericality: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({onlyInteger: true}), + presence: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({message: 'test2'}), + url: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({schemes: ['f']}), +}; + +let constraints: Constraints; +constraints = {}; +constraints = { + a: {date: true}, + b: (value: any, attribute: any, attributeName: any, options: any, constraints: any) => ({datetime: true}), +}; \ No newline at end of file diff --git a/validate.js/validate.js.d.ts b/validate.js/validate.js.d.ts new file mode 100644 index 0000000000..35754e844c --- /dev/null +++ b/validate.js/validate.js.d.ts @@ -0,0 +1,109 @@ +// Type definitions for Validate.js +// Project: https://github.com/ansman/validate.js +// Definitions by: Travis Hill +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace ValidateJS { + + export interface Validator { + message?: string | ((value: any, attribute: any, validatorOptions: any, attributes: any, globalOptions: any) => string); + } + + namespace Validator { + + export interface Date extends Validator { + earliest?: string; + latest?: string; + + notValid?: string; + tooEarly?: string; + tooLate?: string; + } + + export interface DateTime extends Date { + dateOnly?: boolean; + } + + export interface Email extends Validator {} + + export interface Equality extends Validator { + attribute?: string; + comparator?: (v1: any, v2: any) => boolean; + } + + export interface Exclusion extends Validator { + within: any[] | {[key: string]: any}; + } + + export interface Format extends Validator { + pattern: string | RegExp; + flags?: string; + } + + export interface Inclusion extends Validator { + within: any[] | {[key: string]: any}; + } + + export interface Length extends Validator { + is?: number; + minimum?: number; + maximum?: number; + + notValid?: string; + tooLong?: string; + tooShort?: string; + wrongLength?: string; + + tokenizer?: (value: string | any[]) => string | any[]; + } + + export interface Numericality extends Validator { + onlyInteger?: boolean; + strict?: boolean; + greaterThan?: number; + greaterThanOrEqualTo?: number; + equalTo?: number; + lessThanOrEqualTo?: number; + lessThan?: number; + divisibleBy?: number; + odd?: boolean; + even?: boolean; + + notValid?: string; + notInteger?: string; + notGreaterThan?: string; + notGreaterThanOrEqualTo?: string; + notEqualTo?: string; + notLessThanOrEqualTo?: string; + notLessThan?: string; + notDivisibleBy?: string; + notOdd?: string; + notEven?: string; + } + + export interface Presence extends Validator {} + + export interface Url extends Validator { + schemes?: [string | RegExp]; + allowLocal?: boolean; + } + } + + export interface Field { + date?: Validator.Date | boolean | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Date); + datetime?: Validator.DateTime | boolean | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.DateTime); + email?: Validator.Email | boolean | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Email); + equality?: Validator.Equality | string | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Equality); + exclusion?: Validator.Exclusion | any[] | {[key: string]: any} | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Exclusion); + format?: Validator.Format | string | RegExp | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Format); + inclusion?: Validator.Inclusion | any[] | {[key: string]: any} | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Inclusion); + length?: Validator.Length | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Length); + numericality?: Validator.Numericality | boolean | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Numericality); + presence?: Validator.Presence | boolean | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Presence); + url?: Validator.Url | boolean | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Url); + } + + export interface Constraints { + [attribute: string]: Field | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Field); + } +} From ab4e532fa26b68c3bdd914a9dec62476a21bd207 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Fri, 9 Sep 2016 22:57:01 +0800 Subject: [PATCH 445/844] Add new stuff (#11147) * Add new stuff * Correct indent style and variable type --- node/node-4.d.ts | 51 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/node/node-4.d.ts b/node/node-4.d.ts index 6c45fa2f75..daebb4585e 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -2403,6 +2403,57 @@ declare module "constants" { export var W_OK: number; export var X_OK: number; export var UV_UDP_REUSEADDR: number; + export var EDQUOT: number; + export var EMULTIHOP: number; + export var ESTALE: number; + export var O_DIRECT: number; + export var O_DIRECTORY: number; + export var O_NOCTTY: number; + export var O_NOFOLLOW: number; + export var O_NONBLOCK: number; + export var O_SYNC: number; + export var SIGALRM: number; + export var SIGBUS: number; + export var SIGCHLD: number; + export var SIGCONT: number; + export var SIGIO: number; + export var SIGIOT: number; + export var SIGPIPE: number; + export var SIGPOLL: number; + export var SIGPROF: number; + export var SIGPWR: number; + export var SIGQUIT: number; + export var SIGSTKFLT: number; + export var SIGSTOP: number; + export var SIGSYS: number; + export var SIGTRAP: number; + export var SIGTSTP: number; + export var SIGTTIN: number; + export var SIGTTOU: number; + export var SIGUNUSED: number; + export var SIGURG: number; + export var SIGUSR1: number; + export var SIGUSR2: number; + export var SIGVTALRM: number; + export var SIGXCPU: number; + export var SIGXFSZ: number; + export var S_IFBLK: number; + export var S_IFIFO: number; + export var S_IFSOCK: number; + export var S_IRGRP: number; + export var S_IROTH: number; + export var S_IRUSR: number; + export var S_IRWXG: number; + export var S_IRWXO: number; + export var S_IRWXU: number; + export var S_IWGRP: number; + export var S_IWOTH: number; + export var S_IWUSR: number; + export var S_IXGRP: number; + export var S_IXOTH: number; + export var S_IXUSR: number; + export var defaultCipherList: string; + export var defaultCoreCipherList: string; } declare module "process" { From aee853cc8251e007d5e20f84de6bd7250be4c30c Mon Sep 17 00:00:00 2001 From: TonyYang Date: Fri, 9 Sep 2016 23:35:23 +0800 Subject: [PATCH 446/844] [node]Rearrange the order and add missing stuff for os (#11146) * Rearrange the order and add missing something * Correct type of constants --- node/node.d.ts | 142 +++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 132 insertions(+), 10 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index bf5da3f226..905ba4bfd0 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -885,22 +885,144 @@ declare module "os" { internal: boolean; } - export function tmpdir(): string; - export function homedir(): string; - export function endianness(): "BE" | "LE"; export function hostname(): string; - export function type(): string; - export function platform(): string; - export function arch(): string; - export function release(): string; - export function uptime(): number; export function loadavg(): number[]; - export function totalmem(): number; + export function uptime(): number; export function freemem(): number; + export function totalmem(): number; export function cpus(): CpuInfo[]; + export function type(): string; + export function release(): string; export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; - export function userInfo(options?: {encoding: string}): { username: string, uid: number, gid: number, shell: any, homedir: string } + export function homedir(): string; + export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string } + export var constants: { + UV_UDP_REUSEADDR: number, + errno: { + SIGHUP: number; + SIGINT: number; + SIGQUIT: number; + SIGILL: number; + SIGTRAP: number; + SIGABRT: number; + SIGIOT: number; + SIGBUS: number; + SIGFPE: number; + SIGKILL: number; + SIGUSR1: number; + SIGSEGV: number; + SIGUSR2: number; + SIGPIPE: number; + SIGALRM: number; + SIGTERM: number; + SIGCHLD: number; + SIGSTKFLT: number; + SIGCONT: number; + SIGSTOP: number; + SIGTSTP: number; + SIGTTIN: number; + SIGTTOU: number; + SIGURG: number; + SIGXCPU: number; + SIGXFSZ: number; + SIGVTALRM: number; + SIGPROF: number; + SIGWINCH: number; + SIGIO: number; + SIGPOLL: number; + SIGPWR: number; + SIGSYS: number; + SIGUNUSED: number; + }, + signals: { + E2BIG: number; + EACCES: number; + EADDRINUSE: number; + EADDRNOTAVAIL: number; + EAFNOSUPPORT: number; + EAGAIN: number; + EALREADY: number; + EBADF: number; + EBADMSG: number; + EBUSY: number; + ECANCELED: number; + ECHILD: number; + ECONNABORTED: number; + ECONNREFUSED: number; + ECONNRESET: number; + EDEADLK: number; + EDESTADDRREQ: number; + EDOM: number; + EDQUOT: number; + EEXIST: number; + EFAULT: number; + EFBIG: number; + EHOSTUNREACH: number; + EIDRM: number; + EILSEQ: number; + EINPROGRESS: number; + EINTR: number; + EINVAL: number; + EIO: number; + EISCONN: number; + EISDIR: number; + ELOOP: number; + EMFILE: number; + EMLINK: number; + EMSGSIZE: number; + EMULTIHOP: number; + ENAMETOOLONG: number; + ENETDOWN: number; + ENETRESET: number; + ENETUNREACH: number; + ENFILE: number; + ENOBUFS: number; + ENODATA: number; + ENODEV: number; + ENOENT: number; + ENOEXEC: number; + ENOLCK: number; + ENOLINK: number; + ENOMEM: number; + ENOMSG: number; + ENOPROTOOPT: number; + ENOSPC: number; + ENOSR: number; + ENOSTR: number; + ENOSYS: number; + ENOTCONN: number; + ENOTDIR: number; + ENOTEMPTY: number; + ENOTSOCK: number; + ENOTSUP: number; + ENOTTY: number; + ENXIO: number; + EOPNOTSUPP: number; + EOVERFLOW: number; + EPERM: number; + EPIPE: number; + EPROTO: number; + EPROTONOSUPPORT: number; + EPROTOTYPE: number; + ERANGE: number; + EROFS: number; + ESPIPE: number; + ESRCH: number; + ESTALE: number; + ETIME: number; + ETIMEDOUT: number; + ETXTBSY: number; + EWOULDBLOCK: number; + EXDEV: number; + }, + }; + export function arch(): string; + export function platform(): string; + export function tmpdir(): string; + export function tmpDir(): string; + export function getNetworkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; export var EOL: string; + export function endianness(): "BE" | "LE"; } declare module "https" { From ab57464fa2f8315738bd8530d6dff98985112421 Mon Sep 17 00:00:00 2001 From: hriss95 Date: Fri, 9 Sep 2016 16:35:38 +0100 Subject: [PATCH 447/844] Node.d.ts: Update definitions for module "stream" (#11086) * Node.d.ts: Update definitions for module "stream" * Node.d.ts: Fix an issue that caused tests to fail --- node/node.d.ts | 188 +++++++++++++++++++++++++------------------------ 1 file changed, 97 insertions(+), 91 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index 905ba4bfd0..07ecd5fb4a 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2399,102 +2399,108 @@ declare module "crypto" { declare module "stream" { import * as events from "events"; - export class Stream extends events.EventEmitter { + class internal extends events.EventEmitter { pipe(destination: T, options?: { end?: boolean; }): T; } + namespace internal { - export interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - read?: (size?: number) => any; + export class Stream extends internal {} + + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?: (size?: number) => any; + } + + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): Readable; + resume(): Readable; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + } + + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + write?: (chunk: string|Buffer, encoding: string, callback: Function) => any; + writev?: (chunks: {chunk: string|Buffer, encoding: string}[], callback: Function) => any; + } + + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + } + + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements NodeJS.ReadWriteStream { + // Readable + pause(): Duplex; + resume(): Duplex; + // Writeable + writable: boolean; + constructor(opts?: DuplexOptions); + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export interface TransformOptions extends ReadableOptions, WritableOptions { + transform?: (chunk: string|Buffer, encoding: string, callback: Function) => any; + flush?: (callback: Function) => any; + } + + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { + readable: boolean; + writable: boolean; + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: string, callback: Function): void; + _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): Transform; + resume(): Transform; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export class PassThrough extends Transform { } } - export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { - readable: boolean; - constructor(opts?: ReadableOptions); - _read(size: number): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): Readable; - resume(): Readable; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - } - - export interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - objectMode?: boolean; - write?: (chunk: string|Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: {chunk: string|Buffer, encoding: string}[], callback: Function) => any; - } - - export class Writable extends events.EventEmitter implements NodeJS.WritableStream { - writable: boolean; - constructor(opts?: WritableOptions); - _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - readableObjectMode?: boolean; - writableObjectMode?: boolean; - } - - // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements NodeJS.ReadWriteStream { - // Readable - pause(): Duplex; - resume(): Duplex; - // Writeable - writable: boolean; - constructor(opts?: DuplexOptions); - _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export interface TransformOptions extends ReadableOptions, WritableOptions { - transform?: (chunk: string|Buffer, encoding: string, callback: Function) => any; - flush?: (callback: Function) => any; - } - - // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { - readable: boolean; - writable: boolean; - constructor(opts?: TransformOptions); - _transform(chunk: any, encoding: string, callback: Function): void; - _flush(callback: Function): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): Transform; - resume(): Transform; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export class PassThrough extends Transform { } + export = internal; } declare module "util" { From dff108db9a96da9c8f3dcb489b57b389d0f100b3 Mon Sep 17 00:00:00 2001 From: Dominik Palo Date: Fri, 9 Sep 2016 22:15:34 +0200 Subject: [PATCH 448/844] Add missing semicolon --- pdfkit/pdfkit.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pdfkit/pdfkit.d.ts b/pdfkit/pdfkit.d.ts index 85d53c4462..30c8d138da 100644 --- a/pdfkit/pdfkit.d.ts +++ b/pdfkit/pdfkit.d.ts @@ -233,7 +233,7 @@ declare namespace PDFKit { size?: number[]; margin?: number; margins?: { top: number; left: number; bottom: number; right: number }; - layout?: "portrait" | "landscape" + layout?: "portrait" | "landscape"; bufferPages?: boolean; } From fd9ccf78f4897f349d57d081420debb5c144a118 Mon Sep 17 00:00:00 2001 From: Sumit Kumar Maitra Date: Fri, 9 Sep 2016 23:22:00 +0100 Subject: [PATCH 449/844] Updated pasteHTML(...) interface definitions and bumped version to v1.0.3 --- quill/quill-tests.ts | 12 ++++++++++++ quill/quill.d.ts | 5 +++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/quill/quill-tests.ts b/quill/quill-tests.ts index 5116ace525..172b5fd461 100644 --- a/quill/quill-tests.ts +++ b/quill/quill-tests.ts @@ -172,3 +172,15 @@ function test_on_EventType1(){ }); } + +function test_PasteHTML() +{ + var quillEditor = new Quill('#editor'); + quillEditor.pasteHTML('

    Quill Rocks

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

    Quill Rocks

    '); +} diff --git a/quill/quill.d.ts b/quill/quill.d.ts index 885f6bdc34..2e75e14c20 100644 --- a/quill/quill.d.ts +++ b/quill/quill.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Quill v1.0.0 +// Type definitions for Quill v1.0.3 // Project: http://quilljs.com // Definitions by: Sumit // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -49,7 +49,8 @@ declare namespace QuillJS { insertText(index: number, text: string, source?: sourceType): void; insertText(index: number, text: string, format: string, value: string, source?: sourceType): void; insertText(index: number, text: string, formats: formatsType, source?: sourceType): void; - pasteHTML(): string; + pasteHTML(index: number, html: string, source?:sourceType): string; + pasteHTML(html:string, source?: sourceType): string; setContents(delta: DeltaStatic, source?: sourceType): void; setText(text: string, source?: sourceType): void; update(source?: string): void; From ab1d6b03d0b3383eee40f4f67b8b061927ec5981 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Mon, 12 Sep 2016 01:20:04 +0900 Subject: [PATCH 450/844] TypeScript-STL v1.0.8 & Samchon-Framework v2.0 beta-8 --- samchon-framework/samchon-framework.d.ts | 1466 +++++++++++++--------- typescript-stl/typescript-stl.d.ts | 1074 +++++++++------- 2 files changed, 1484 insertions(+), 1056 deletions(-) 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/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>; /** From f105740dced564894ee5a12c36fce6a82af9a849 Mon Sep 17 00:00:00 2001 From: Ben Mosher Date: Mon, 12 Sep 2016 08:45:01 -0400 Subject: [PATCH 451/844] superagent: updates for feedback on #11055 --- superagent/superagent-tests.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/superagent/superagent-tests.ts b/superagent/superagent-tests.ts index a91914eaae..283244ac85 100644 --- a/superagent/superagent-tests.ts +++ b/superagent/superagent-tests.ts @@ -310,6 +310,7 @@ request request .get('/blob') .responseType('blob') - .end(function(err, res){ - assert.deepEqual(res.xhr.response instanceof Blob, true); + .end(function (err, res) { + assert(res.xhr instanceof XMLHttpRequest) + assert(res.xhr.response instanceof Blob); }); From a99a95390e5bfc09078fcd0597c395b2ccae370f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Kov=C3=A1cs?= Date: Tue, 13 Sep 2016 10:50:15 +0200 Subject: [PATCH 452/844] [tether-drop] Remove 'drop' property since it is undocumented --- tether-drop/tether-drop.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/tether-drop/tether-drop.d.ts b/tether-drop/tether-drop.d.ts index c908ba399e..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 drop: HTMLElement; public tether: Tether; public open(): void; public close(): void; From 605baa5cb44469c9bd6d2caa70b6b9812d500224 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Kov=C3=A1cs?= Date: Tue, 13 Sep 2016 10:51:45 +0200 Subject: [PATCH 453/844] [tether-drop] Fix test containing 'drop' property --- tether-drop/tether-drop-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tether-drop/tether-drop-tests.ts b/tether-drop/tether-drop-tests.ts index 403f8d7421..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.drop.appendChild(document.createElement("div")); +d.content.appendChild(document.createElement("div")); d.tether.position(); d.on("open", () => false); From 33377a68598194d155764feb4a4ef33f606b220a Mon Sep 17 00:00:00 2001 From: Tomas Date: Tue, 13 Sep 2016 11:37:10 +0100 Subject: [PATCH 454/844] Fixing removeAllListeners definition - argument optional --- wolfy87-eventemitter/wolfy87-eventemitter.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wolfy87-eventemitter/wolfy87-eventemitter.d.ts b/wolfy87-eventemitter/wolfy87-eventemitter.d.ts index 8291c50c11..d9af289d1a 100644 --- a/wolfy87-eventemitter/wolfy87-eventemitter.d.ts +++ b/wolfy87-eventemitter/wolfy87-eventemitter.d.ts @@ -405,14 +405,14 @@ declare namespace Wolfy87EventEmitter { * * Added to mirror the node API. */ - removeAllListeners(event: string): EventEmitter; + removeAllListeners(event?: string): EventEmitter; /** * Alias of removeEvent. * * Added to mirror the node API. */ - removeAllListeners(event: RegExp): EventEmitter; + removeAllListeners(event?: RegExp): EventEmitter; /** * Emits an event of your choice. From d34c7a7cdd8b58b40eabc3fcc0ac90d799fca4ba Mon Sep 17 00:00:00 2001 From: Marc Date: Tue, 13 Sep 2016 10:35:48 -0400 Subject: [PATCH 455/844] requirejs.RequireConfig Add a missing signature for urlArgs property of the RequireConfig object. --- requirejs/require.d.ts | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/requirejs/require.d.ts b/requirejs/require.d.ts index 3905945187..1c5b4088c1 100644 --- a/requirejs/require.d.ts +++ b/requirejs/require.d.ts @@ -185,8 +185,28 @@ interface RequireConfig { * * @example * urlArgs: "bust= + (new Date()).getTime() + * + * As of RequireJS 2.2.0, urlArgs can be a function. If a + * function, it will receive the module ID and the URL as + * parameters, and it should return a string that will be added + * to the end of the URL. Return an empty string if no args. + * Be sure to take care of adding the '?' or '&' depending on + * the existing state of the URL. + * + * @example + + * requirejs.config({ + * urlArgs: function(id, url) { + * var args = 'v=1'; + * if (url.indexOf('view.html') !== -1) { + * args = 'v=2' + * } + * + * return (url.indexOf('?') === -1 ? '?' : '&') + args; + * } + * }); **/ - urlArgs?: string; + urlArgs?: string | { (id: string, url: string): string; }; /** * Specify the value for the type="" attribute used for script From feae95f169c4892f7e525cbe9d7f677785c99210 Mon Sep 17 00:00:00 2001 From: Gary Roberts Date: Wed, 14 Sep 2016 09:03:34 +0100 Subject: [PATCH 456/844] Update react-router.d.ts Changed react-router RouteComponentProps comment to properly reflect routeParams resolving to type string (not number). As per documentation here: https://github.com/ReactTraining/react-router/blob/master/docs/API.md#routeparams --- react-router/react-router.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index fb19dca42d..767cca1e2f 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. ... // ... From 874a60bc6803c2ce7eb1103be41be5a203e5a323 Mon Sep 17 00:00:00 2001 From: Marcin Kral Date: Wed, 14 Sep 2016 13:39:53 +0200 Subject: [PATCH 457/844] Add Pure and Stateless components to withRouter definition (#10959) * Add Pure and Stateless components to withRouter definition * Add missing type parameter --- react-router/react-router.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index fb19dca42d..5df21529e6 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -247,7 +247,7 @@ declare namespace ReactRouter { isActive: (pathOrLoc: H.LocationDescriptor, indexOnly?: boolean) => boolean } - function withRouter>(component: C): C + function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C /* utils */ From b1546040789c7f2da20ac97067837e63182f6e16 Mon Sep 17 00:00:00 2001 From: Bastien Caudan Date: Wed, 14 Sep 2016 13:40:39 +0200 Subject: [PATCH 458/844] Add colors strip and stripColors methods (#11160) --- colors/colors-tests.ts | 2 ++ colors/colors.d.ts | 9 +++++++++ 2 files changed, 11 insertions(+) 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; From c393c1f1f75bfc8e57df5eb6b70c11eebc28d742 Mon Sep 17 00:00:00 2001 From: ersimont Date: Wed, 14 Sep 2016 07:41:24 -0400 Subject: [PATCH 459/844] support `$injector.get('$resource')` (#11161) --- angularjs/angular-resource.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index 441a7e1d3d..3deed5d2fa 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -186,6 +186,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 From 202e18feddce6512b2e7a89262c13c0f703f859b Mon Sep 17 00:00:00 2001 From: Dominik Palo Date: Wed, 14 Sep 2016 13:41:52 +0200 Subject: [PATCH 460/844] Add typings for node-rio (#11162) --- rpio/rpio-tests.ts | 105 +++++++++++++ rpio/rpio.d.ts | 372 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 477 insertions(+) create mode 100644 rpio/rpio-tests.ts create mode 100644 rpio/rpio.d.ts 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; + } +} From f237a9af8e7a59dc2fa1ce78f9b84e328d985364 Mon Sep 17 00:00:00 2001 From: Matt Lewis Date: Wed, 14 Sep 2016 12:42:34 +0100 Subject: [PATCH 461/844] Add types for the date-fns library (#11163) --- date-fns/date-fns-tests.ts | 16 + date-fns/date-fns.d.ts | 1195 ++++++++++++++++++++++++++++++++++++ 2 files changed, 1211 insertions(+) create mode 100644 date-fns/date-fns-tests.ts create mode 100644 date-fns/date-fns.d.ts 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; +} + From 20e557ecad41d9a9e4af7fbab58f90366c72aa94 Mon Sep 17 00:00:00 2001 From: David Pires Date: Wed, 14 Sep 2016 12:44:54 +0100 Subject: [PATCH 462/844] Added type definitions for scrollreveal (#10855) * Added type definitions for scrollreveal * fixed implicit any * remove IScrollReveal --- scrollreveal/scrollreveal-tests.ts | 74 ++++++++++++++++++++++++++++++ scrollreveal/scrollreveal.d.ts | 68 +++++++++++++++++++++++++++ 2 files changed, 142 insertions(+) create mode 100644 scrollreveal/scrollreveal-tests.ts create mode 100644 scrollreveal/scrollreveal.d.ts 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 From be0ba281b67575b3b626a6bbb15b152add97244e Mon Sep 17 00:00:00 2001 From: Stefan Thomas Date: Wed, 14 Sep 2016 04:45:59 -0700 Subject: [PATCH 463/844] Fix typo for core-js/.../min-safe-integer (#11166) Fix a typo in the `core-js/(library/)fn/number/min-safe-integer` module name. --- core-js/core-js.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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; } From 66d2cc80d8bb5ccfcf37b40e6197205f04182a15 Mon Sep 17 00:00:00 2001 From: "shinichi.kogai" Date: Wed, 14 Sep 2016 20:47:43 +0900 Subject: [PATCH 464/844] add point-in-polygon/point-in-polygon.d.ts (#11169) --- point-in-polygon/point-in-polygon-tests.ts | 6 ++++++ point-in-polygon/point-in-polygon.d.ts | 8 ++++++++ 2 files changed, 14 insertions(+) create mode 100644 point-in-polygon/point-in-polygon-tests.ts create mode 100644 point-in-polygon/point-in-polygon.d.ts 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; +} From 6f4b149a52e3b894b68c7181aada547e23beb58b Mon Sep 17 00:00:00 2001 From: Humberto Machado Date: Wed, 14 Sep 2016 09:04:16 -0300 Subject: [PATCH 465/844] Add _router definition in Application. Using to get all registred routes (#11006) --- express-serve-static-core/express-serve-static-core.d.ts | 5 +++++ 1 file changed, 5 insertions(+) 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 { From 0a51f69a36bb73214cdadfacc06def3cb4ba762f Mon Sep 17 00:00:00 2001 From: ShMcK Date: Wed, 14 Sep 2016 05:13:51 -0700 Subject: [PATCH 466/844] Add `toThrowError` test matcher (#11171) Add `toThrowError` test docs. See Jest Docs [toThrowError](https://facebook.github.io/jest/docs/api.html#tothrowerror-error). --- jest/jest.d.ts | 1 + 1 file changed, 1 insertion(+) 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; From 2affe4c63bc3f2a667804ffee4b8b00d74cadbc8 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Wed, 14 Sep 2016 21:14:17 +0900 Subject: [PATCH 467/844] TypeScript-STL v1.0.8 & Samchon-Framework v2.0 beta-8 (#11172) --- samchon-framework/samchon-framework.d.ts | 1466 +++++++++++++--------- typescript-stl/typescript-stl.d.ts | 1074 +++++++++------- 2 files changed, 1484 insertions(+), 1056 deletions(-) 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/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>; /** From d9ed548addd8d5eae953e28e4dfe98c2d6a03568 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 14 Sep 2016 20:15:15 +0800 Subject: [PATCH 468/844] Delete deprecated functions (#11173) --- node/node.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index 820521e43c..c2a8f71239 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1019,8 +1019,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"; } From f7b0b1c8a030760ff4e87bbb6fa4b28393da33fe Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 14 Sep 2016 20:20:09 +0800 Subject: [PATCH 469/844] Correct assert.fail parameters (#11176) --- node/node.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/node/node.d.ts b/node/node.d.ts index c2a8f71239..a9112d47a4 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2596,7 +2596,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; From d1171f6895907d555e0a78bca773c9fba3be14f4 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 14 Sep 2016 20:20:31 +0800 Subject: [PATCH 470/844] [node.d.ts] Implement function tests for assert (#11175) * Implement function tests for assert * Implement function tests for assert - Node v4.x --- node/node-4-tests.ts | 17 ++++++++--------- node/node-tests.ts | 17 ++++++++--------- 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 0162951454..35fe3553a6 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -34,7 +34,7 @@ namespace assert_tests{ 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; @@ -43,21 +43,20 @@ namespace assert_tests{ assert.equal(3, "3", "uses == comparator"); - // TODO: assert.fail + assert.fail(1, 2, undefined, '>'); - // TODO: assert.ifError + assert.ifError(0); - assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses === comparator"); + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - // TODO: assert.notDeepStrictEqual - - // TODO: assert.notEqual + assert.notEqual(1, 2, "uses != comparator"); assert.notStrictEqual(2, "2", "uses === comparator"); - // TODO: assert.ok + assert.ok(true); + assert.ok(1); - // TODO: assert.strictEqual + assert.strictEqual(1, 1, "uses === comparator"); assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); } diff --git a/node/node-tests.ts b/node/node-tests.ts index 651df8ca09..7e010bc9a3 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -36,7 +36,7 @@ namespace assert_tests{ 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; @@ -45,21 +45,20 @@ namespace assert_tests{ assert.equal(3, "3", "uses == comparator"); - // TODO: assert.fail + assert.fail(1, 2, undefined, '>'); - // TODO: assert.ifError + assert.ifError(0); - assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses === comparator"); + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - // TODO: assert.notDeepStrictEqual - - // TODO: assert.notEqual + assert.notEqual(1, 2, "uses != comparator"); assert.notStrictEqual(2, "2", "uses === comparator"); - // TODO: assert.ok + assert.ok(true); + assert.ok(1); - // TODO: assert.strictEqual + assert.strictEqual(1, 1, "uses === comparator"); assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); } From 684fa0d89400dff7497ce9fec7ab3f7376cd27bc Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 14 Sep 2016 20:21:03 +0800 Subject: [PATCH 471/844] [node.d.ts] Correct NodeBuffer.toJSON type (#11177) * Correct NodeBuffer.toJSON type * Correct NodeBuffer.toJSON type in Node v4.x --- node/node-4.d.ts | 2 +- node/node.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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.d.ts b/node/node.d.ts index a9112d47a4..8c4123f283 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -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; From 1b2c971798ad303824af74973de1a2b5b9acaf79 Mon Sep 17 00:00:00 2001 From: Joshua Efiong Date: Wed, 14 Sep 2016 13:23:06 +0100 Subject: [PATCH 472/844] Added GeoShape classes to typedefs (#11178) * Added GeoShape classes to typedefs * Circle style can be SpatialStyle.Options --- heremaps/heremaps.d.ts | 315 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 312 insertions(+), 3 deletions(-) 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; } } From 5ee054ac95f68355c05b8d168b9a2f1eb4a581f8 Mon Sep 17 00:00:00 2001 From: hriss95 Date: Wed, 14 Sep 2016 13:26:40 +0100 Subject: [PATCH 473/844] [Node.d.ts]: Update definitions for module "crypto" (#11186) --- node/node.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node/node.d.ts b/node/node.d.ts index 8c4123f283..76a42f4013 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2434,6 +2434,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" { From 2e7debf76d12149b4eee2c2e26ce9a1065b31369 Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Wed, 14 Sep 2016 05:41:56 -0700 Subject: [PATCH 474/844] Update to Electron 1.3.5 (#11096) --- github-electron/github-electron-main-tests.ts | 57 +++++++++ github-electron/github-electron.d.ts | 117 +++++++++++++++++- 2 files changed, 171 insertions(+), 3 deletions(-) diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index bebf0b99c8..966465ed3a 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -240,6 +240,63 @@ app.setUserTasks([ } ]); app.setUserTasks([]); + +app.setJumpList([ + { + type: 'custom', + name: 'Recent Projects', + items: [ + { type: 'file', path: 'C:\\Projects\\project1.proj' }, + { type: 'file', path: 'C:\\Projects\\project2.proj' } + ] + }, + { // has a name so type is assumed to be "custom" + name: 'Tools', + items: [ + { + type: 'task', + title: 'Tool A', + program: process.execPath, + args: '--run-tool-a', + iconPath: process.execPath, + iconIndex: 0, + description: 'Runs Tool A' + }, + { + type: 'task', + title: 'Tool B', + program: process.execPath, + args: '--run-tool-b', + iconPath: process.execPath, + iconIndex: 0, + description: 'Runs Tool B' + }] + }, + { + type: 'frequent' + }, + { // has no name and no type so type is assumed to be "tasks" + items: [ + { + type: 'task', + title: 'New Project', + program: process.execPath, + args: '--new-project', + description: 'Create a new project.' + }, + { + type: 'separator' + }, + { + type: 'task', + title: 'Recover Project', + program: process.execPath, + args: '--recover-project', + description: 'Recover Project' + }] + } +]); + if (app.isUnityRunning()) { } if (app.isAccessibilitySupportEnabled()) { diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 7d10fce465..3dc72d7075 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.3.4 +// Type definitions for Electron v1.3.5 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -199,7 +199,7 @@ declare namespace Electron { * All windows will be closed immediately without asking user * and the before-quit and will-quit events will not be emitted. */ - exit(exitCode: number): void; + exit(exitCode?: number): void; /** * Relaunches the app when current instance exits. * @@ -333,6 +333,19 @@ declare namespace Electron { * Note: This API is only available on Windows. */ setUserTasks(tasks: Task[]): boolean; + /** + * Note: This API is only available on Windows. + */ + getJumpListSettings(): JumpListSettings; + /** + * Sets or removes a custom Jump List for the application. + * + * If categories is null the previously set custom Jump List (if any) will be replaced + * by the standard Jump List for the app (managed by Windows). + * + * Note: This API is only available on Windows. + */ + setJumpList(categories: JumpListCategory[]): SetJumpListResult; /** * This method makes your application a Single Instance Application instead of allowing * multiple instances of your app to run, this will ensure that only a single instance @@ -560,6 +573,89 @@ declare namespace Electron { iconIndex?: number; } + /** + * ok - Nothing went wrong. + * error - One or more errors occured, enable runtime logging to figure out the likely cause. + * invalidSeparatorError - An attempt was made to add a separator to a custom category in the Jump List. + * Separators are only allowed in the standard Tasks category. + * fileTypeRegistrationError - An attempt was made to add a file link to the Jump List + * for a file type the app isn't registered to handle. + * customCategoryAccessDeniedError - Custom categories can't be added to the Jump List + * due to user privacy or group policy settings. + */ + type SetJumpListResult = 'ok' | 'error' | 'invalidSeparatorError' | 'fileTypeRegistrationError' | 'customCategoryAccessDeniedError'; + + interface JumpListSettings { + /** + * The minimum number of items that will be shown in the Jump List. + */ + minItems: number; + /** + * Items that the user has explicitly removed from custom categories in the Jump List. + */ + removedItems: JumpListItem[]; + } + + interface JumpListCategory { + /** + * tasks - Items in this category will be placed into the standard Tasks category. + * frequent - Displays a list of files frequently opened by the app, the name of the category and its items are set by Windows. + * recent - Displays a list of files recently opened by the app, the name of the category and its items are set by Windows. + * custom - Displays tasks or file links, name must be set by the app. + */ + type?: 'tasks' | 'frequent' | 'recent' | 'custom'; + /** + * Must be set if type is custom, otherwise it should be omitted. + */ + name?: string; + /** + * Array of JumpListItem objects if type is tasks or custom, otherwise it should be omitted. + */ + items?: JumpListItem[]; + } + + interface JumpListItem { + /** + * task - A task will launch an app with specific arguments. + * separator - Can be used to separate items in the standard Tasks category. + * file - A file link will open a file using the app that created the Jump List. + */ + type: 'task' | 'separator' | 'file'; + /** + * Path of the file to open, should only be set if type is file. + */ + path?: string; + /** + * Path of the program to execute, usually you should specify process.execPath which opens the current program. + * Should only be set if type is task. + */ + program?: string; + /** + * The command line arguments when program is executed. Should only be set if type is task. + */ + args?: string; + /** + * The text to be displayed for the item in the Jump List. Should only be set if type is task. + */ + title?: string; + /** + * Description of the task (displayed in a tooltip). Should only be set if type is task. + */ + description?: string; + /** + * The absolute path to an icon to be displayed in a Jump List, which can be an arbitrary + * resource file that contains an icon (e.g. .ico, .exe, .dll). + * You can usually specify process.execPath to show the program icon. + */ + iconPath?: string; + /** + * The index of the icon in the resource file. If a resource file contains multiple icons + * this value can be used to specify the zero-based index of the icon that should be displayed + * for this task. If a resource file contains only one icon, this property should be set to zero. + */ + iconIndex?: number; + } + interface LoginItemSettings { /** * True if the app is set to open at login. @@ -3595,7 +3691,7 @@ declare namespace Electron { interface WebContentsStatic { /** - * @returns An array of all web contents. This will contain web contents for all windows, + * @returns An array of all WebContents instances. This will contain web contents for all windows, * webviews, opened devtools, and devtools extension background pages. */ getAllWebContents(): WebContents[]; @@ -3603,6 +3699,10 @@ declare namespace Electron { * @returns The web contents that is focused in this application, otherwise returns null. */ getFocusedWebContents(): WebContents; + /** + * Find a WebContents instance according to its ID. + */ + fromId(id: number): WebContents; } /** @@ -4971,6 +5071,17 @@ declare namespace Electron { * See webContents.sendInputEvent for detailed description of event object. */ sendInputEvent(event: SendInputEvent): void + /** + * Changes the zoom factor to the specified factor. + * Zoom factor is zoom percent divided by 100, so 300% = 3.0. + */ + setZoomFactor(factor: number): void; + /** + * Changes the zoom level to the specified level. + * The original size is 0 and each increment above or below represents + * zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. + */ + setZoomLevel(level: number): void; /** * Shows pop-up dictionary that searches the selected word on the page. * Note: This API is available only on macOS. From c4186178260604b5b45f7cbc10d7525640e24460 Mon Sep 17 00:00:00 2001 From: Riad Loukili Date: Wed, 14 Sep 2016 13:44:48 +0100 Subject: [PATCH 475/844] AppBar type fix (#11192) Styles should be CSS properties not string. ;) --- material-ui/material-ui.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index f9dcbcfb38..2430923d9d 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -513,8 +513,8 @@ declare namespace __MaterialUI { iconClassNameRight?: string; iconElementLeft?: React.ReactElement; iconElementRight?: React.ReactElement; - iconStyleRight?: string; - iconStyleLeft?: string; + iconStyleRight?: React.CSSProperties; + iconStyleLeft?: React.CSSProperties; onLeftIconButtonTouchTap?: TouchTapEventHandler; onRightIconButtonTouchTap?: TouchTapEventHandler; onTitleTouchTap?: TouchTapEventHandler; From 007f8af1dcb7a849a9fe9f8c60fdde5fd594cb7c Mon Sep 17 00:00:00 2001 From: ShMcK Date: Wed, 14 Sep 2016 05:45:16 -0700 Subject: [PATCH 476/844] Add Atom Grammars (#11194) See [Atom Grammar Registry Docs](https://atom.io/docs/api/v1.10.2/GrammarRegistry). Atom grammars can be found by typings `atom.grammars` into the console. --- atom/atom.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) 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; From ef12b9812631c89256a70e9269ea8021e008c738 Mon Sep 17 00:00:00 2001 From: Marcy Sutton Date: Wed, 14 Sep 2016 05:45:38 -0700 Subject: [PATCH 477/844] add axe-core definition (#11195) --- axe-core/axe-core-tests.ts | 91 +++++++++++++++++++++ axe-core/axe-core.d.ts | 159 +++++++++++++++++++++++++++++++++++++ 2 files changed, 250 insertions(+) create mode 100644 axe-core/axe-core-tests.ts create mode 100644 axe-core/axe-core.d.ts 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; +} From 4280cc2e71bb8211727116b5a442f7317b5e816c Mon Sep 17 00:00:00 2001 From: Graham Mendick Date: Wed, 14 Sep 2016 13:45:59 +0100 Subject: [PATCH 478/844] Updated typings and tests for Navigation 3.0.0 (#11196) --- navigation/navigation-tests.ts | 5 +++-- navigation/navigation.d.ts | 22 ++++++++++++---------- 2 files changed, 15 insertions(+), 12 deletions(-) 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 */ From c404aa6f7bb825b5385b554b66a3e2c861bd7175 Mon Sep 17 00:00:00 2001 From: linusbrolin Date: Wed, 14 Sep 2016 14:46:59 +0200 Subject: [PATCH 479/844] Added typings for the mongoose-sequence plugin (#11201) --- mongoose-sequence/mongoose-sequence-tests.ts | 52 ++++++++++++++++++++ mongoose-sequence/mongoose-sequence.d.ts | 36 ++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 mongoose-sequence/mongoose-sequence-tests.ts create mode 100644 mongoose-sequence/mongoose-sequence.d.ts 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 = _; +} From 73e5a5026641eda668d1c787bfa25b065645e539 Mon Sep 17 00:00:00 2001 From: linusbrolin Date: Wed, 14 Sep 2016 14:47:12 +0200 Subject: [PATCH 480/844] Added an overload for the default mongoose plugin function (#11202) This fixes typing errors when other plugins (with different types of options) are used on the same model as this one. --- passport-local-mongoose/passport-local-mongoose.d.ts | 3 +++ 1 file changed, 3 insertions(+) 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( From 3a0684743e9443b8693a980ff3353d20066de0c7 Mon Sep 17 00:00:00 2001 From: Thomas Champagne Date: Wed, 14 Sep 2016 14:49:27 +0200 Subject: [PATCH 481/844] Must be "tooltips" (plurar) instead of "tooltip" (#11180) ...must be "tooltips" (plurar) instead of "tooltip" in ChartOptions My custom callback given in "ChartTooltipOptions.custom" was never called... :/ "tooltips" (plurar) is OK Take a look @ http://www.chartjs.org/docs/#advanced-usage-external-tooltips --- chart.js/chart.js.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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; From 5262c27b6ec4786e543c32ac83ef0b5b687987b5 Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Wed, 14 Sep 2016 15:51:20 +0300 Subject: [PATCH 482/844] Fix `redux-promise` export (#11200) `redux-promise` is using an old version of Babel which transpiles `default` export to: ```js exports['default'] = promiseMiddleware; module.exports = promiseMiddleware; ``` Fix the declaration file to respect this. --- redux-promise/redux-promise-tests.ts | 2 +- redux-promise/redux-promise.d.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) 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; +} From 5f23898c6fbc0b08b918b37030dedbda660a5907 Mon Sep 17 00:00:00 2001 From: sguest Date: Wed, 14 Sep 2016 07:56:56 -0500 Subject: [PATCH 483/844] videojs corrections (#11193) ready() is chainable, on() will provide event object to callback, off() can be called without callback and without event name --- videojs/videojs.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) 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; From 3cbdc08f81f5d1b5d188fda0893936dc89cb4742 Mon Sep 17 00:00:00 2001 From: Ian Ker-Seymer Date: Wed, 14 Sep 2016 08:57:21 -0400 Subject: [PATCH 484/844] Add typings for react-virtualized (#11148) --- react-virtualized/react-virtualized-tests.tsx | 309 ++++++++++++++++++ react-virtualized/react-virtualized.d.ts | 123 +++++++ 2 files changed, 432 insertions(+) create mode 100644 react-virtualized/react-virtualized-tests.tsx create mode 100644 react-virtualized/react-virtualized.d.ts 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 { } +} From e9bd268321e6e3cfcebcd633054b3a4b2c4db578 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Wed, 14 Sep 2016 14:58:56 +0200 Subject: [PATCH 485/844] Add definition for "bunnymq" and "strftime". (#11188) * Add definition for "bunnymq". * Add definition for "strftime". --- bunnymq/bunnymq-tests.ts | 36 +++++++++++ bunnymq/bunnymq.d.ts | 120 +++++++++++++++++++++++++++++++++++++ strftime/strftime-tests.ts | 37 ++++++++++++ strftime/strftime.d.ts | 72 ++++++++++++++++++++++ 4 files changed, 265 insertions(+) create mode 100644 bunnymq/bunnymq-tests.ts create mode 100644 bunnymq/bunnymq.d.ts create mode 100644 strftime/strftime-tests.ts create mode 100644 strftime/strftime.d.ts 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/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; +} From 2b69abecc831e4da5d360044efb74e13396bf7a9 Mon Sep 17 00:00:00 2001 From: Ayman Nedjmeddine Date: Wed, 14 Sep 2016 15:03:11 +0200 Subject: [PATCH 486/844] Updated Validator API to v5.7.0 (#11209) --- validator/validator-tests.ts | 31 +++++++++++-------- validator/validator.d.ts | 59 +++++++++++++++++++++--------------- 2 files changed, 52 insertions(+), 38 deletions(-) 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; } From 489541498b7a896cfa99348afb56c9530a60c85d Mon Sep 17 00:00:00 2001 From: Jonathon T Date: Wed, 14 Sep 2016 23:11:04 +1000 Subject: [PATCH 487/844] [angular-ui-scroll] Include startIndex parameter on adapter reload() method (#11216) As per docs here: https://github.com/angular-ui/ui-scroll `reload()` includes a `startIndex` parameterl; --- angular-ui-scroll/angular-ui-scroll.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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. * From ef6b6ef139d11e9fe25fe668e8e5b0fa0ba8a9f7 Mon Sep 17 00:00:00 2001 From: Meno Abels Date: Wed, 14 Sep 2016 15:11:22 +0200 Subject: [PATCH 488/844] Added https type to Websocket.Server (#11213) * Added https type to Websocket.Server Hi, the current typing misses to pass to the Websocket.Server server option a https Server. Cheers meno * * added a test * fix the missing typo of http(s) * improve the test --- ws/ws-tests.ts | 9 ++++++++- ws/ws.d.ts | 3 ++- 2 files changed, 10 insertions(+), 2 deletions(-) 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; From 8193bc8f6eaf97fc1272c7c503c03d999b379a89 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 14 Sep 2016 21:13:43 +0800 Subject: [PATCH 489/844] [node.d.ts] Add definite events for Readable and Writable (#11217) * Add definite events for Readable and Writable * Delete comments in cluster * Recovery cluster * Remove interface extends events.EventEmitter --- node/node.d.ts | 157 ++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 141 insertions(+), 16 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index 76a42f4013..76c5c05c94 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 @@ -588,7 +588,7 @@ 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; @@ -599,7 +599,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 +629,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,7 +655,7 @@ 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; @@ -1040,7 +1040,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 { @@ -1853,7 +1853,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; @@ -2196,7 +2196,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; @@ -2212,7 +2212,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)[]; @@ -2445,7 +2445,7 @@ declare module "stream" { } namespace internal { - export class Stream extends internal {} + export class Stream extends internal { } export interface ReadableOptions { highWaterMark?: number; @@ -2467,14 +2467,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 { @@ -2486,6 +2545,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 { @@ -2511,7 +2636,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; } @@ -2949,7 +3074,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; } From 81197a3926d297f76fc4bb4b77d260100c429843 Mon Sep 17 00:00:00 2001 From: rgozim Date: Wed, 14 Sep 2016 14:16:59 +0100 Subject: [PATCH 490/844] Change #Extend PolyMouseEvent interface from MouseEvent interface (#11218) PolyMouseEvent should inherit from MouseEvent according to google documentation https://developers.google.com/maps/documentation/javascript/3.exp/reference#PolyMouseEvent --- googlemaps/google.maps.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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; From 3423aa94ffdbe8f4ded33733318e08020a2d6ca8 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 14 Sep 2016 21:17:36 +0800 Subject: [PATCH 491/844] connection are socket are same in IncomingMessage (#11219) --- node/node.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/node/node.d.ts b/node/node.d.ts index 76c5c05c94..2094959e6e 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -659,7 +659,7 @@ declare module "http" { httpVersion: string; httpVersionMajor: string; httpVersionMinor: string; - connection: any; + connection: net.Socket; headers: any; rawHeaders: string[]; trailers: any; From ff71c3d812952fb56c73ae0ff57b0d0cf4b220d8 Mon Sep 17 00:00:00 2001 From: Nick Graef Date: Wed, 14 Sep 2016 08:20:03 -0500 Subject: [PATCH 492/844] enforce action hash type in $resource() (#11212) --- angularjs/angular-resource.d.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index 3deed5d2fa..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 From b73aaa36d313393d8aaa5411669cf4e0f6b16759 Mon Sep 17 00:00:00 2001 From: Leo Rudberg Date: Wed, 14 Sep 2016 08:20:28 -0500 Subject: [PATCH 493/844] Fixes #10684 (#10751) I kept the deprecated `pick` declarations, but added the proposed (JSDoc-influenced) [deprecation annotation](https://github.com/Microsoft/TypeScript/issues/390) to them. The added `pickone` and `pickset` declarations have identical types to their respective `pick` flavors. --- chance/chance.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) 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[]; From f46e80640829b7dc43a4030868c1e82889acdabd Mon Sep 17 00:00:00 2001 From: Craig Date: Wed, 14 Sep 2016 06:21:51 -0700 Subject: [PATCH 494/844] types(selenium-webdriver): version 2.53.1 (#10852) - moving selenium-webdriver.d.ts to selenium-webdriver-2.44.0.d.ts - adding in selenium-webdriver.d.ts for version 2.53.1 --- angular-protractor/angular-protractor.d.ts | 2 +- protractor-helpers/protractor-helpers.d.ts | 3 +- .../protractor-http-mock.d.ts | 2 +- .../selenium-webdriver-2.44.0.d.ts | 5393 +++++++++++++++++ .../selenium-webdriver-tests.ts | 249 +- selenium-webdriver/selenium-webdriver.d.ts | 3992 +++++++----- 6 files changed, 7999 insertions(+), 1642 deletions(-) create mode 100644 selenium-webdriver/selenium-webdriver-2.44.0.d.ts diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index d33eeddace..add8264b7e 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -3,7 +3,7 @@ // Definitions by: Bill Armstrong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace protractor { //region Wrapped webdriver Items diff --git a/protractor-helpers/protractor-helpers.d.ts b/protractor-helpers/protractor-helpers.d.ts index 20aad94c54..16d67cfbb9 100644 --- a/protractor-helpers/protractor-helpers.d.ts +++ b/protractor-helpers/protractor-helpers.d.ts @@ -5,7 +5,7 @@ /// /// -/// +/// // ElementArrayFinder @@ -108,4 +108,3 @@ declare module "protractor-helpers" { function getFilteredConsoleErrors() : webdriver.promise.IThenable; // TODO - discuss handling in IE } - diff --git a/protractor-http-mock/protractor-http-mock.d.ts b/protractor-http-mock/protractor-http-mock.d.ts index 29d6dfb276..2300246e43 100644 --- a/protractor-http-mock/protractor-http-mock.d.ts +++ b/protractor-http-mock/protractor-http-mock.d.ts @@ -3,7 +3,7 @@ // Definitions by: Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace mock { interface ProtractorHttpMock { diff --git a/selenium-webdriver/selenium-webdriver-2.44.0.d.ts b/selenium-webdriver/selenium-webdriver-2.44.0.d.ts new file mode 100644 index 0000000000..548048b695 --- /dev/null +++ b/selenium-webdriver/selenium-webdriver-2.44.0.d.ts @@ -0,0 +1,5393 @@ +// Type definitions for Selenium WebDriverJS 2.44.0 +// Project: https://code.google.com/p/selenium/ +// Definitions by: Bill Armstrong , Yuki Kokubun +// 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?: webdriver.Capabilities, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: Options, opt_service?: any, 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 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; + + + /** + * Converts this instance to its JSON wire protocol representation. Note this + * function is an implementation not intended for general use. + * @return {{args: !Array., + * binary: (string|undefined), + * detach: boolean, + * extensions: !Array., + * localState: (Object|undefined), + * logFile: (string|undefined), + * prefs: (Object|undefined)}} The JSON wire protocol representation + * of this instance. + */ + toJSON(): IOptionsValues; + } + + /** + * 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): ServiceBuilder; + setStdio(config: any[]): 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(): any; + } + + /** + * 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(): any; + + /** + * 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: any): void; +} + +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; + } + + /** + * A WebDriver client for Firefox. + * + * @extends {webdriver.WebDriver} + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|webdriver.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link webdriver.Capabilities}, or as a raw hash + * object. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + * @constructor + */ + constructor(opt_config?: webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: any, opt_flow?: webdriver.promise.ControlFlow); + } + + /** + * Configuration options for the FirefoxDriver. + */ + class Options { + /** + * @constructor + */ + constructor(); + + /** + * 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): Options; + setProfile(profile: Profile): 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): Options; + setBinary(binary: Binary): Options; + + + /** + * Sets the logging preferences for the new session. + * @param {webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + + /** + * Sets the proxy to use. + * + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts these options to a {@link webdriver.Capabilities} instance. + * + * @return {!webdriver.Capabilities} A new capabilities object. + */ + toCapabilities(opt_remote?: any): webdriver.Capabilities; + } + + /** + * 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; + } +} + +declare namespace executors { + /** + * Creates a command executor that uses WebDriver's JSON wire protocol. + * @param url The server's URL, or a promise that will resolve to that URL. + * @returns {!webdriver.CommandExecutor} The new command executor. + */ + function createExecutor(url: string): webdriver.CommandExecutor; + function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; +} + +declare namespace webdriver { + + namespace error { + interface IErrorCode { + SUCCESS: number; + + NO_SUCH_ELEMENT: number; + NO_SUCH_FRAME: number; + UNKNOWN_COMMAND: number; + UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. + STALE_ELEMENT_REFERENCE: number; + ELEMENT_NOT_VISIBLE: number; + INVALID_ELEMENT_STATE: number; + UNKNOWN_ERROR: number; + ELEMENT_NOT_SELECTABLE: number; + JAVASCRIPT_ERROR: number; + XPATH_LOOKUP_ERROR: number; + TIMEOUT: number; + NO_SUCH_WINDOW: number; + INVALID_COOKIE_DOMAIN: number; + UNABLE_TO_SET_COOKIE: number; + MODAL_DIALOG_OPENED: number; + UNEXPECTED_ALERT_OPEN: number; + NO_SUCH_ALERT: number; + NO_MODAL_DIALOG_OPEN: number; + SCRIPT_TIMEOUT: number; + INVALID_ELEMENT_COORDINATES: number; + IME_NOT_AVAILABLE: number; + IME_ENGINE_ACTIVATION_FAILED: number; + INVALID_SELECTOR_ERROR: number; + SESSION_NOT_CREATED: number; + MOVE_TARGET_OUT_OF_BOUNDS: number; + SQL_DATABASE_ERROR: number; + INVALID_XPATH_SELECTOR: number; + INVALID_XPATH_SELECTOR_RETURN_TYPE: number; + // The following error codes are derived straight from HTTP return codes. + METHOD_NOT_ALLOWED: number; + } + + var ErrorCode: IErrorCode; + + /** + * Error extension that includes error status codes from the WebDriver wire + * protocol: + * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes + * + * @extends {Error} + */ + class Error { + + //region Constructors + + /** + * @param {!bot.ErrorCode} code The error's status code. + * @param {string=} opt_message Optional error message. + * @constructor + */ + constructor(code: number, opt_message?: string); + + //endregion + + //region Static Properties + + /** + * Status strings enumerated in the W3C WebDriver working draft. + * @enum {string} + * @see http://www.w3.org/TR/webdriver/#status-codes + */ + static State: { + ELEMENT_NOT_SELECTABLE: string; + ELEMENT_NOT_VISIBLE: string; + IME_ENGINE_ACTIVATION_FAILED: string; + IME_NOT_AVAILABLE: string; + INVALID_COOKIE_DOMAIN: string; + INVALID_ELEMENT_COORDINATES: string; + INVALID_ELEMENT_STATE: string; + INVALID_SELECTOR: string; + JAVASCRIPT_ERROR: string; + MOVE_TARGET_OUT_OF_BOUNDS: string; + NO_SUCH_ALERT: string; + NO_SUCH_DOM: string; + NO_SUCH_ELEMENT: string; + NO_SUCH_FRAME: string; + NO_SUCH_WINDOW: string; + SCRIPT_TIMEOUT: string; + SESSION_NOT_CREATED: string; + STALE_ELEMENT_REFERENCE: string; + SUCCESS: string; + TIMEOUT: string; + UNABLE_TO_SET_COOKIE: string; + UNEXPECTED_ALERT_OPEN: string; + UNKNOWN_COMMAND: string; + UNKNOWN_ERROR: string; + UNSUPPORTED_OPERATION: string; + }; + + //endregion + + //region Properties + + /** + * This error's status code. + * @type {!bot.ErrorCode} + */ + code: number; + + /** @type {string} */ + state: string; + + /** @override */ + message: string; + + /** @override */ + name: string; + + /** @override */ + stack: string; + + /** + * Flag used for duck-typing when this code is embedded in a Firefox extension. + * This is required since an Error thrown in one component and then reported + * to another will fail instanceof checks in the second component. + * @type {boolean} + */ + isAutomationError: boolean; + + //endregion + + //region Methods + + /** @return {string} The string representation of this error. */ + toString(): string; + + //endregion + } + } + + namespace logging { + + /** + * A hash describing log preferences. + * @typedef {Object.} + */ + class Preferences { + setLevel(type: string, level: ILevel): void; + toJSON(): { [key: string]: string }; + } + + interface IType { + /** Logs originating from the browser. */ + BROWSER: string; + /** Logs from a WebDriver client. */ + CLIENT: string; + /** Logs from a WebDriver implementation. */ + DRIVER: string; + /** Logs related to performance. */ + PERFORMANCE: string; + /** Logs from the remote server. */ + SERVER: string; + } + + /** + * Common log types. + * @enum {string} + */ + var Type: IType; + + /** + * Logging levels. + * @enum {{value: number, name: webdriver.logging.LevelName}} + */ + interface ILevel { + value: number; + name: string; + } + + interface ILevelValues { + ALL: ILevel; + DEBUG: ILevel; + INFO: ILevel; + WARNING: ILevel; + SEVERE: ILevel; + OFF: ILevel; + } + + var Level: ILevelValues; + + /** + * 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): ILevel; + function getLevel(nameOrValue: number): ILevel; + + interface IEntryJSON { + level: string; + message: string; + timestamp: number; + type: string; + } + + /** + * A single log entry. + */ + class Entry { + + //region Constructors + + /** + * @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: ILevel, message: string, opt_timestamp?:number, opt_type?:string); + constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); + + //endregion + + //region Public Properties + + /** @type {!webdriver.logging.Level} */ + level: ILevel; + + /** @type {string} */ + message: string; + + /** @type {number} */ + timestamp: number; + + /** @type {string} */ + type: string; + + //endregion + + //region Static Methods + + /** + * Converts a {@link goog.debug.LogRecord} into a + * {@link webdriver.logging.Entry}. + * @param {!goog.debug.LogRecord} logRecord The record to convert. + * @param {string=} opt_type The log type. + * @return {!webdriver.logging.Entry} The converted entry. + */ + static fromClosureLogRecord(logRecord: any, opt_type?:string): Entry; + + //endregion + + //region Methods + + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + + //endregion + } + } + + 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|!webdriver.promise.Promise.)>} arr An array of + * promises to wait on. + * @return {!webdriver.promise.Promise.>} 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: Promise[]): 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(!webdriver.promise.ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!webdriver.promise.Promise} 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 {!webdriver.promise.Promise} 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.|webdriver.promise.Promise.>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array.): ( + * boolean|webdriver.promise.Promise.)} 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: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise; + function filter(arr: Promise, fn: (element: T, 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 {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. + */ + 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.|webdriver.promise.Promise.>)} 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: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function map(arr: Promise, fn: (element: T, index: number, array: T[]) => 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 {!webdriver.promise.Promise} The rejected promise. + */ + function rejected(opt_reason?: any): Promise; + + /** + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. + * @param {!Function} fn The function to wrap. + * @return {!webdriver.promise.Promise} 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. + *

    
    +         * webdriver.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. + *

    
    +         * webdriver.promise.consume(function* () {
    +         *   yield webdriver.promise.delayed(250).then(function() {
    +         *     throw Error('boom');
    +         *   });
    +         * }).thenCatch(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 {!webdriver.promise.Promise.} 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 {!webdriver.promise.Promise} A new promise. + */ + function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: 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; + * webdriver.promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!webdriver.promise.Promise} 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 {!webdriver.promise.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. + * + * @extends {goog.debug.Error} + * @final + */ + class CancellationError { + /** + * @param {string=} opt_msg The cancellation message. + * @constructor + */ + constructor(opt_msg?: string); + + name: string; + message: 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 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: T) => Promise, opt_errback?: (error: any) => any): 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: T) => R, opt_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().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 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): 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 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: T) => Promise, opt_errback?: (error: any) => any): 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: T) => R, opt_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().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 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): 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: webdriver.promise.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 webdriver.promise.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 {promise.ControlFlow=} opt_flow The control flow + * this instance was created under. Defaults to the currently active flow. + * @constructor + */ + 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(reason: any): 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?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * 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?: (value: T) => R, opt_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().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 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): 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 stacktrace { + /** + * Class representing one stack frame. + */ + class Frame { + /** + * @param {(string|undefined)} context Context object, empty in case of global + * functions or if the browser doesn't provide this information. + * @param {(string|undefined)} name Function name, empty in case of anonymous + * functions. + * @param {(string|undefined)} alias Alias of the function if available. For + * example the function name will be 'c' and the alias will be 'b' if the + * function is defined as a.b = function c() {};. + * @param {(string|undefined)} path File path or URL including line number and + * optionally column number separated by colons. + * @constructor + */ + constructor(context?: string, name?: string, alias?: string, path?: string); + + /** + * @return {string} The function name or empty string if the function is + * anonymous and the object field which it's assigned to is unknown. + */ + getName(): string; + + + /** + * @return {string} The url or empty string if it is unknown. + */ + getUrl(): string; + + + /** + * @return {number} The line number if known or -1 if it is unknown. + */ + getLine(): number; + + + /** + * @return {number} The column number if known and -1 if it is unknown. + */ + getColumn(): number; + + + /** + * @return {boolean} Whether the stack frame contains an anonymous function. + */ + isAnonymous(): boolean; + + + /** + * Converts this frame to its string representation using V8's stack trace + * format: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + * @return {string} The string representation of this frame. + * @override + */ + toString(): string; + } + + /** + * Stores a snapshot of the stack trace at the time this instance was created. + * The stack trace will always be adjusted to exclude this function call. + */ + class Snapshot { + /** + * @param {number=} opt_slice The number of frames to remove from the top of + * the generated stack trace. + * @constructor + */ + constructor(opt_slice?: number); + + /** + * @return {!Array.} The parsed stack trace. + */ + getStacktrace(): Frame[]; + } + + /** + * Formats an error's stack trace. + * @param {!(Error|goog.testing.JsUnitException)} error The error to format. + * @return {!(Error|goog.testing.JsUnitException)} The formatted error. + */ + function format(error: any): any; + + /** + * Gets the native stack trace if available otherwise follows the call chain. + * The generated trace will exclude all frames up to and including the call to + * this function. + * @return {!Array.} The frames of the stack trace. + */ + function get(): Frame[]; + + /** + * Whether the current browser supports stack traces. + * + * @type {boolean} + * @const + */ + var BROWSER_SUPPORTED: boolean; + } + + 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 {@code 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| + * webdriver.Locator|webdriver.By.Hash| + * function(!webdriver.WebDriver): !webdriver.WebElement)} frame + * The frame identifier. + * @return {!until.Condition.} A new condition. + */ + function ableToSwitchToFrame(frame: number|WebElement|Locator|By.Hash|((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 {!until.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 {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.} The new condition. + */ + function elementLocated(locator: Locator|By.Hash|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: Locator|By.Hash|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; + } + + /** + * Enumeration of the buttons used in the advanced interactions API. + * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. + * @enum {number} + */ + interface IButton { + LEFT: number; + MIDDLE: number; + RIGHT: number; + } + + var Button: IButton; + + /** + * 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} + */ + interface IKey { + NULL: string; + CANCEL: string; // ^break + HELP: string; + BACK_SPACE: string; + TAB: string; + CLEAR: string; + RETURN: string; + ENTER: string; + SHIFT: string; + CONTROL: string; + ALT: string; + PAUSE: string; + ESCAPE: string; + SPACE: string; + PAGE_UP: string; + PAGE_DOWN: string; + END: string; + HOME: string; + ARROW_LEFT: string; + LEFT: string; + ARROW_UP: string; + UP: string; + ARROW_RIGHT: string; + RIGHT: string; + ARROW_DOWN: string; + DOWN: string; + INSERT: string; + DELETE: string; + SEMICOLON: string; + EQUALS: string; + + NUMPAD0: string; // number pad keys + NUMPAD1: string; + NUMPAD2: string; + NUMPAD3: string; + NUMPAD4: string; + NUMPAD5: string; + NUMPAD6: string; + NUMPAD7: string; + NUMPAD8: string; + NUMPAD9: string; + MULTIPLY: string; + ADD: string; + SEPARATOR: string; + SUBTRACT: string; + DECIMAL: string; + DIVIDE: string; + + F1: string; // function keys + F2: string; + F3: string; + F4: string; + F5: string; + F6: string; + F7: string; + F8: string; + F9: string; + F10: string; + F11: string; + F12: string; + + COMMAND: string; // Apple command key + META: string; // alias for Windows key + + /** + * Simulate pressing many keys at once in a "chord". Takes a sequence of + * {@link webdriver.Key}s or strings, appends each of the values to a string, + * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns + * the resultant string. + * + * Note: when the low-level webdriver key handlers see Keys.NULL, active + * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. + * + * @param {...string} var_args The key sequence to concatenate. + * @return {string} The null-terminated key sequence. + * @see http://code.google.com/p/webdriver/issues/detail?id=79 + */ + chord: (...var_args: string[]) => string; + } + + var Key: IKey; + + /** + * Class for defining sequences of complex user interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + *

    Example:

    
    +     *   new webdriver.ActionSequence(driver).
    +     *       keyDown(webdriver.Key.SHIFT).
    +     *       click(element1).
    +     *       click(element2).
    +     *       dragAndDrop(element3, element4).
    +     *       keyUp(webdriver.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 An optional offset, in pixels. + * Defaults to (0, 0). + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseMove(location: WebElement, opt_offset?: ILocation): ActionSequence; + mouseMove(location: 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 + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseDown(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + mouseDown(opt_elementOrButton?: number): 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 + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseUp(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + mouseUp(opt_elementOrButton?: number): 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 {!webdriver.ActionSequence} A self reference. + */ + dragAndDrop(element: WebElement, location: WebElement): ActionSequence; + dragAndDrop(element: WebElement, location: 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|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + click(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + click(opt_elementOrButton?: number): 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 + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + doubleClick(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + doubleClick(opt_elementOrButton?: number): 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: string): 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: string): 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: any[]): 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}). + */ + interface Alert { + + //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; + + /** + * 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();
    +     *     });
    +     * 
    + * + * @param {!webdriver.WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!webdriver.promise.Thenable.} alert A thenable + * that will be fulfilled with the promised alert. + * @constructor + * @extends {webdriver.Alert} + * @implements {webdriver.promise.Thenable.} + * @final + */ + interface AlertPromise extends Alert, webdriver.promise.IThenable { + } + + /** + * An error returned to indicate that there is an unhandled modal dialog on the + * current page. + * @extends {bot.Error} + */ + interface UnhandledAlertError extends webdriver.error.Error { + //region Methods + + /** + * @return {string} The text displayed with the unhandled alert. + */ + getAlertText(): string; + + /** + * @return {!webdriver.Alert} The open alert. + * @deprecated Use {@link #getAlertText}. This method will be removed in + * 2.45.0. + */ + getAlert(): Alert; + + + //endregion + } + + /** + * Recognized browser names. + * @enum {string} + */ + interface IBrowser { + ANDROID: string; + CHROME: string; + FIREFOX: 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; + } + + class Builder { + + //region Constructors + + /** + * @constructor + */ + constructor(); + + //endregion + + //region Methods + + /** + * Creates a new WebDriver client based on this builder's current + * configuration. + * + * @return {!webdriver.WebDriver} A new WebDriver instance. + * @throws {Error} If the current configuration is invalid. + */ + build(): WebDriver; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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): Builder; + setLoggingPrefs(prefs: { [key: string]: string }): 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 {!webdriver.ProxyConfig} config The configuration to use. + * @return {!Builder} A self reference. + */ + setProxy(config: ProxyConfig): 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 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: Capabilities): Builder; + withCapabilities(capabilities: any): Builder; + + //endregion + } + + /** + * 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); + constructor(opt_other?: any); + + //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): Capabilities; + merge(other: any): 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): Capabilities; + setLoggingPrefs(prefs: { [key: string]: string }): 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 {!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; + } + + 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 {@code webdriver.Command} objects. + */ + interface CommandExecutor { + /** + * 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 + * {@link bot.response.ResponseObject} object. + * @param {!webdriver.Command} command The command to execute. + * @param {function(Error, !bot.response.ResponseObject=)} callback the function + * to invoke when the command response is ready. + */ + execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; + } + + /** + * 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 {!Array.<{fn: !Function, oneshot: boolean, + * scope: (Object|undefined)}>} The registered listeners for + * the given event type. + */ + listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: any;}>; + + /** + * Registers a listener. + * @param {string} type The type of event to listen for. + * @param {!Function} listenerFn 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. + */ + addListener(type: string, listenerFn: Function, opt_scope?:any): 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} listenerFn 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, listenerFn: any, opt_scope?: any): EventEmitter; + + /** + * An alias for {@code #addListener()}. + * @param {string} type The type of event to listen for. + * @param {!Function} listenerFn 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, listenerFn: 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. + */ + interface WebDriverNavigation { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverNavigation; + + //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. + */ + interface WebDriverOptions { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: webdriver.WebDriver): WebDriverOptions; + + //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 {!webdriver.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): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: 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(): WebDriverLogs; + + /** + * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver + * timeouts. + */ + timeouts(): WebDriverTimeouts; + + /** + * @return {!webdriver.WebDriver.Window} The interface for managing the + * current window. + */ + window(): WebDriverWindow; + + //endregion + } + + /** + * An interface for managing timeout behavior for WebDriver instances. + */ + interface WebDriverTimeouts { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverTimeouts; + + //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. + */ + interface WebDriverWindow { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverWindow; + + //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. + */ + interface WebDriverLogs { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverLogs; + + //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: string): 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. + */ + interface WebDriverTargetLocator { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverTargetLocator; + + //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. + *

    + * If the frame is specified by a number, the command will switch to the frame + * by its (zero-based) index into the {@code window.frames} collection. + *

    + * If the frame is specified by a string, the command will select the frame by + * its name or ID. To select sub-frames, simply separate the frame names/IDs by + * dots. As an example, "main.child" will select the frame with the name "main" + * and then its child "child". + *

    + * If the specified frame can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. + * @param {string|number} nameOrIndex The frame locator. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the specified frame. + */ + frame(nameOrIndex: string): webdriver.promise.Promise; + frame(nameOrIndex: number): 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 {@code webdriver.WebDriver#getWindowHandles}). + *

    + * If the specificed window can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. + * @param {string} nameOrHandle The name or window handle of the window to + * switch focus to. + * @return {!webdriver.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 alert dialog. This command + * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal + * dialog is not currently open. + * @return {!webdriver.Alert} 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 {!(webdriver.Session|webdriver.promise.Promise)} session Either a + * known session or a promise that will be resolved to a session. + * @param {!webdriver.CommandExecutor} executor The executor to use when + * sending commands to the browser. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + * @constructor + */ + constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + + //endregion + + //region Static Properties + + static Navigation: WebDriverNavigation; + static Options: WebDriverOptions; + static Timeouts: WebDriverTimeouts; + static Window: WebDriverWindow; + static Logs: WebDriverLogs; + static TargetLocator: WebDriverTargetLocator; + + //endregion + + //region StaticMethods + + /** + * Creates a new WebDriver client for an existing session. + * @param {!webdriver.CommandExecutor} executor Command executor to use when + * querying for session details. + * @param {string} sessionId ID of the session to attach to. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under. Defaults to the + * {@link webdriver.promise.controlFlow() currently active} control flow. + * @return {!webdriver.WebDriver} A new client for the specified session. + */ + static attachToSession(executor: CommandExecutor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + + /** + * Creates a new WebDriver session. + * @param {!webdriver.CommandExecutor} executor The executor to create the new + * session with. + * @param {!webdriver.Capabilities} desiredCapabilities The desired + * capabilities for the new session. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under, including the initial session creation. + * Defaults to the {@link webdriver.promise.controlFlow() currently active} + * control flow. + * @return {!webdriver.WebDriver} The driver for the newly created session. + */ + static createSession(executor: CommandExecutor, 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 {@code webdriver.Command} to be executed by this driver's + * {@code webdriver.CommandExecutor}. + * @param {!webdriver.Command} command The command to schedule. + * @param {string} description A description of the command for debugging. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the command result. + */ + schedule(command: Command, description: string): webdriver.promise.Promise; + + + /** + * Sets the {@linkplain webdriver.FileDetector file detector} that should be + * used with this instance. + * @param {webdriver.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 webdriver.ActionSequence#perform} is + * called. Example: + *

    
    +         *   driver.actions().
    +         *       mouseDown(element1).
    +         *       mouseMove(element2).
    +         *       mouseUp().
    +         *       perform();
    +         * 
    + * @return {!webdriver.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 webdriver.TouchSequence#perform} is + * called. Example: + * + * driver.touchActions(). + * tap(element1). + * doubleTap(element2). + * perform(); + * + * @return {!webdriver.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, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: 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 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 = driver.findElement(firstVisibleLink); + * + * function firstVisibleLink(driver) { + * var links = driver.findElements(By.tagName('a')); + * return webdriver.promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; + * }); + * } + * + * When running in the browser, a WebDriver cannot manipulate DOM elements + * directly; it may do so only through a {@link webdriver.WebElement} reference. + * This function may be used to generate a WebElement from a DOM element. A + * reference to the DOM element will be stored in a known location and this + * driver will attempt to retrieve it through {@link #executeScript}. If the + * element cannot be found (eg, it belongs to a different document than the + * one this instance is currently focused on), a + * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The + * locator to use. + * @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(locatorOrElement: Locator|By.Hash|WebElement|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 {!(webdriver.Locator|webdriver.By.Hash|Element| + * Function)} locatorOrElement The locator to use, or the actual + * DOM element to be located by the server. + * @return {!webdriver.promise.Promise.} A promise that will resolve + * with whether the element is present on the page. + */ + isElementPresent(locatorOrElement: Locator|By.Hash|WebElement|Function): webdriver.promise.Promise; + + /** + * Schedule a command to search for multiple elements on the page. + * + * @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 resolve to an array of WebElements. + */ + findElements(locator: Locator|By.Hash|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 screenshot of the entire display containing the browser + *
    + * + * @return {!webdriver.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(): WebDriverOptions; + + /** + * @return {!webdriver.WebDriver.Navigation} The navigation interface for this + * instance. + */ + navigate(): WebDriverNavigation; + + /** + * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for + * this instance. + */ + switchTo(): WebDriverTargetLocator; + + //endregion + } + + interface IWebElementId { + ELEMENT: string; + } + + /** + * 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 {@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: Locator|By.Hash|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: Locator|By.Hash|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: Locator|By.Hash|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.WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!(webdriver.promise.Promise.| + * webdriver.WebElement.Id)} id The server-assigned opaque ID for the + * underlying DOM element. + * @constructor + */ + constructor(driver: WebDriver, id: webdriver.promise.Promise|IWebElementId); + + /** + * Wire protocol definition of a WebElement ID. + * @typedef {{ELEMENT: string}} + * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + */ + static Id: IWebElementId; + + /** + * The property key used in the wire protocol to indicate that a JSON object + * contains the ID of a WebElement. + * @type {string} + * @const + */ + static ELEMENT_KEY: string; + + + /** + * @return {!webdriver.WebDriver} The parent driver for this instance. + */ + getDriver(): WebDriver; + + /** + * 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 {!(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: Locator|By.Hash|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: Locator|By.Hash|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: Locator|By.Hash|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 + * 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 {@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 {!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 (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 {@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; + + /** + * Returns the raw ID string ID for this element. + * @return {!webdriver.promise.Promise} A promise that resolves to this + * element's raw ID as a string value. + * @package + */ + getRawId(): webdriver.promise.Promise; + + /** @override */ + serialize(): 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; + + /** + * Compares to WebElements for equality. + * @param {!webdriver.WebElement} a A WebElement. + * @param {!webdriver.WebElement} b A WebElement. + * @return {!webdriver.promise.Promise} A promise that will be resolved to + * whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): 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 { + /** + * 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; + } + + namespace By { + /** + * Locates elements that have a specific class name. The returned locator + * is equivalent to searching for elements with the CSS selector ".clazz". + * + * @param {string} className The class name to search for. + * @return {!webdriver.Locator} 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 + */ + function className(value: string): Locator; + + /** + * Locates elements using a CSS selector. For browsers that do not support + * CSS selectors, WebDriver implementations may return an + * {@linkplain bot.Error.State.INVALID_SELECTOR invalid selector} error. An + * implementation may, however, emulate the CSS selector API. + * + * @param {string} selector The CSS selector to use. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html + */ + function css(value: string): Locator; + + /** + * Locates an element by its ID. + * + * @param {string} id The ID to search for. + * @return {!webdriver.Locator} The new locator. + */ + function id(value: string): Locator; + + /** + * Locates link elements whose {@linkplain webdriver.WebElement#getText visible + * text} matches the given string. + * + * @param {string} text The link text to search for. + * @return {!webdriver.Locator} The new locator. + */ + function linkText(value: string): Locator; + + /** + * 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): !webdriver.promise.Promise} A new, + * JavaScript-based locator function. + */ + function js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates elements whose {@code name} attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!webdriver.Locator} The new locator. + */ + function name(value: string): Locator; + + /** + * 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 {!webdriver.Locator} The new locator. + */ + function partialLinkText(value: string): Locator; + + /** + * Locates elements with a given tag name. The returned locator is + * equivalent to using the + * [getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) + * DOM function. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html + */ + function tagName(value: string): Locator; + + /** + * 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 {@code "//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 {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ + function xpath(value: string): Locator; + + /** + * 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 Hash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + } + + /** + * An element locator. + */ + class Locator { + /** + * An element locator. + * @param {string} using The type of strategy to use for this locator. + * @param {string} value The search target of this locator. + * @constructor + */ + constructor(using: string, value: string); + + + /** + * Maps {@link webdriver.By.Hash} keys to the appropriate factory function. + * @type {!Object.} + * @const + */ + static Strategy: { + className: typeof webdriver.By.className; + css: typeof webdriver.By.css; + id: typeof webdriver.By.id; + js: typeof webdriver.By.js; + linkText: typeof webdriver.By.linkText; + name: typeof webdriver.By.name; + partialLinkText: typeof webdriver.By.partialLinkText; + tagName: typeof webdriver.By.tagName; + xpath: typeof webdriver.By.xpath; + }; + + /** + * Verifies that a {@code value} is a valid locator to use for searching for + * elements on the page. + * + * @param {*} value The value to check is a valid locator. + * @return {!(webdriver.Locator|Function)} A valid locator object or function. + * @throws {TypeError} If the given value is an invalid locator. + */ + static checkLocator(value: any): Locator | Function; + + /** + * The search strategy to use when searching for an element. + * @type {string} + */ + using: string; + + /** + * The search target for this locator. + * @type {string} + */ + value: string; + + /** @return {string} String representation of this locator. */ + toString(): string; + } + + /** + * 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); + constructor(id: string, capabilities: any); + + //endregion + + //region Methods + + /** + * @return {string} This session's ID. + */ + getId(): string; + + /** + * @return {!webdriver.Capabilities} This session's capabilities. + */ + getCapabilities(): 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/firefox' { + export = firefox; +} + +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-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 345a8efc5b..1ab39ba02a 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -3,7 +3,7 @@ function TestChromeDriver() { var driver: chrome.Driver = new chrome.Driver(); driver = new chrome.Driver(webdriver.Capabilities.chrome()); - driver = new chrome.Driver(webdriver.Capabilities.chrome(), new webdriver.promise.ControlFlow()); + driver = new chrome.Driver(webdriver.Capabilities.chrome(), new remote.DriverService('executable', new chrome.Options()), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -31,7 +31,6 @@ function TestChromeOptions() { options = options.setUserPreferences("preferences"); var capabilities: webdriver.Capabilities = options.toCapabilities(); capabilities = options.toCapabilities(webdriver.Capabilities.chrome()); - var values: chrome.IOptionsValues = options.toJSON(); } function TestServiceBuilder() { @@ -52,7 +51,7 @@ function TestServiceBuilder() { function TestChromeModule() { var service: any = chrome.getDefaultService(); - chrome.setDefaultService({}); + chrome.setDefaultService(new remote.DriverService('executable', new chrome.Options())); } function TestBinary() { @@ -66,8 +65,8 @@ function TestBinary() { function TestFirefoxDriver() { var driver: firefox.Driver = new firefox.Driver(); - driver = new chrome.Driver(webdriver.Capabilities.firefox()); - driver = new chrome.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); + driver = new firefox.Driver(webdriver.Capabilities.firefox()); + driver = new firefox.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -82,7 +81,6 @@ function TestFirefoxOptions() { options = options.setProfile(new firefox.Profile()); options = options.setProxy({ proxyType: "proxy" }); var capabilities: webdriver.Capabilities = options.toCapabilities(); - var capabilities: webdriver.Capabilities = options.toCapabilities({}); } function TestFirefoxProfile() { @@ -108,7 +106,7 @@ function TestFirefoxProfile() { } function TestExecutors() { - var exec: webdriver.CommandExecutor = executors.createExecutor("url"); + var exec: webdriver.Executor = executors.createExecutor("url"); var promise: webdriver.promise.Promise; exec = executors.createExecutor(promise); } @@ -144,7 +142,9 @@ function TestActionSequence() { build(); var sequence: webdriver.ActionSequence = new webdriver.ActionSequence(driver); - var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + var promise: webdriver.promise.Promise; + element = new webdriver.WebElement(driver, promise); // Click sequence = sequence.click(); @@ -187,7 +187,6 @@ function TestActionSequence() { // SendKeys sequence = sequence.sendKeys("A", "B", "C"); - sequence = sequence.sendKeys(["A", "B", "C"]); sequence.perform().then(function () { }); } @@ -196,7 +195,7 @@ function TestTouchSequence() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); var sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver); @@ -319,9 +318,9 @@ function TestCommand() { command = command.setParameters({ param: 123 }); } -function TestCommandExecutor() { - var c: webdriver.CommandExecutor = { execute: function (command: webdriver.Command, callback: (error: Error, obj: any) => any) { } }; - c.execute(new webdriver.Command('name'), function (error: Error, response: any) { }); +function TestDeferredExecutor() { + var promise: webdriver.promise.Promise; + var executor: webdriver.DeferredExecutor = new webdriver.DeferredExecutor(promise); } function TestCommandName() { @@ -458,7 +457,7 @@ function TestEventEmitter() { } function TestKey() { - var key: string; + var key: webdriver.Key; key = webdriver.Key.ADD; key = webdriver.Key.ALT; @@ -520,35 +519,15 @@ function TestKey() { key = webdriver.Key.SUBTRACT; key = webdriver.Key.TAB; key = webdriver.Key.UP; - - key = webdriver.Key.chord(webdriver.Key.NUMPAD0, webdriver.Key.NUMPAD1); } -function TestLocator() { +function TestBy() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.Locator = new webdriver.Locator('class name', 'class'); + var locator: webdriver.By = new webdriver.By('class name', 'class'); - var locatorOrFn: webdriver.Locator|Function; - - locatorOrFn = webdriver.Locator.Strategy.className; - locatorOrFn = webdriver.Locator.Strategy.css; - locatorOrFn = webdriver.Locator.Strategy.id; - locatorOrFn = webdriver.Locator.Strategy.js; - locatorOrFn = webdriver.Locator.Strategy.linkText; - locatorOrFn = webdriver.Locator.Strategy.name; - locatorOrFn = webdriver.Locator.Strategy.partialLinkText; - locatorOrFn = webdriver.Locator.Strategy.tagName; - locatorOrFn = webdriver.Locator.Strategy.xpath; - - locatorOrFn = webdriver.Locator.checkLocator(locator); - locatorOrFn = webdriver.Locator.checkLocator({ className: 'class' }); - locatorOrFn = webdriver.Locator.checkLocator(Error); - - var using: string = locator.using; - var value: string = locator.value; var str: string = locator.toString(); locator = webdriver.By.className('class'); @@ -563,7 +542,7 @@ function TestLocator() { // Can import "By" without import declarations var By = webdriver.By; - var locatorHash: webdriver.By.Hash; + var locatorHash: webdriver.ByHash; locatorHash = { className: 'class' }; locatorHash = { css: 'css' }; locatorHash = { id: 'id' }; @@ -591,9 +570,7 @@ function TestSession() { function TestUnhandledAlertError() { var someFunc = function (error: webdriver.UnhandledAlertError) { - var baseError: webdriver.error.Error = error; - - var alert: webdriver.Alert = error.getAlert(); + var baseError: Error = error; var str: string = error.getAlertText(); str = error.toString(); } @@ -614,7 +591,7 @@ function TestWebDriverLogs() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var logs: webdriver.WebDriverLogs = new webdriver.WebDriver.Logs(driver); + 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[]) { }); @@ -625,7 +602,7 @@ function TestWebDriverNavigation() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var navigation: webdriver.WebDriverNavigation = new webdriver.WebDriver.Navigation(driver); + var navigation: webdriver.Navigation = new webdriver.Navigation(driver); navigation.back().then(function () { }); navigation.forward().then(function () { }); @@ -638,7 +615,7 @@ function TestWebDriverOptions() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var options: webdriver.WebDriverOptions = new webdriver.WebDriver.Options(driver); + var options: webdriver.Options = new webdriver.Options(driver); var promise: webdriver.promise.Promise; // Add Cookie @@ -654,9 +631,9 @@ function TestWebDriverOptions() { options.getCookie('name').then(function (cookies: webdriver.IWebDriverOptionsCookie) { }); options.getCookies().then(function (cookies: webdriver.IWebDriverOptionsCookie[]) { }); - var logs: webdriver.WebDriverLogs = options.logs(); - var timeouts: webdriver.WebDriverTimeouts = options.timeouts(); - var window: webdriver.WebDriverWindow = options.window(); + var logs: webdriver.Logs = options.logs(); + var timeouts: webdriver.Timeouts = options.timeouts(); + var window: webdriver.Window = options.window(); } function TestWebDriverTargetLocator() { @@ -664,13 +641,12 @@ function TestWebDriverTargetLocator() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.WebDriverTargetLocator = new webdriver.WebDriver.TargetLocator(driver); + 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('name'); promise = locator.frame(1); promise = locator.window('nameOrHandle'); } @@ -680,7 +656,7 @@ function TestWebDriverTimeouts() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var timeouts: webdriver.WebDriverTimeouts = new webdriver.WebDriver.Timeouts(driver); + var timeouts: webdriver.Timeouts = new webdriver.Timeouts(driver); var promise: webdriver.promise.Promise; promise = timeouts.implicitlyWait(123); @@ -693,7 +669,7 @@ function TestWebDriverWindow() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var window: webdriver.WebDriverWindow = new webdriver.WebDriver.Window(driver); + var window: webdriver.Window = new webdriver.Window(driver); var locationPromise: webdriver.promise.Promise; var sizePromise: webdriver.promise.Promise; var voidPromise: webdriver.promise.Promise; @@ -708,7 +684,7 @@ function TestWebDriverWindow() { function TestWebDriver() { var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); var sessionPromise: webdriver.promise.Promise; - var executor: webdriver.CommandExecutor = executors.createExecutor("http://someserver"); + 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); @@ -746,15 +722,11 @@ function TestWebDriver() { // findElement var element: webdriver.WebElement; element = driver.findElement(webdriver.By.id('ABC')); - element = driver.findElement({id: 'ABC'}); element = driver.findElement(webdriver.By.js('function(){}')); - element = driver.findElement({js: 'function(){}'}); // findElements driver.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); - driver.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); driver.findElements(webdriver.By.js('function(){}')).then(function (elements: webdriver.WebElement[]) { }); - driver.findElements({ js: 'function(){}' }).then(function (elements: webdriver.WebElement[]) { }); voidPromise = driver.get('http://www.google.com'); driver.getAllWindowHandles().then(function (handles: string[]) { }); @@ -766,13 +738,11 @@ function TestWebDriver() { stringPromise = driver.getWindowHandle(); booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); - booleanPromise = driver.isElementPresent({className: 'ABC'}); booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); - booleanPromise = driver.isElementPresent({js: 'function(){}'}); - var options: webdriver.WebDriverOptions = driver.manage(); - var navigation: webdriver.WebDriverNavigation = driver.navigate(); - var locator: webdriver.WebDriverTargetLocator = driver.switchTo(); + 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); @@ -795,7 +765,7 @@ function TestWebDriver() { function TestSerializable() { var serializable: webdriver.Serializable; - var serial: string|webdriver.promise.Promise = serializable.serialize(); + var serial: string|webdriver.promise.IThenable = serializable.serialize(); } function TestWebElement() { @@ -803,10 +773,10 @@ function TestWebElement() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var promise: webdriver.promise.Promise; + var promise: webdriver.promise.Promise; var element: webdriver.WebElement; - element = new webdriver.WebElement(driver, { ELEMENT: 'ID' }); + element = new webdriver.WebElement(driver, 'elementId'); element = new webdriver.WebElement(driver, promise); var voidPromise: webdriver.promise.Promise; @@ -817,13 +787,8 @@ function TestWebElement() { voidPromise = element.click(); element = element.findElement(webdriver.By.id('ABC')); - element = element.findElement({id: 'ABC'}); - element.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); - element.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); - booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); - booleanPromise = element.isElementPresent({className: 'ABC'}); stringPromise = element.getAttribute('class'); stringPromise = element.getCssValue('display'); @@ -840,14 +805,11 @@ function TestWebElement() { voidPromise = element.sendKeys('A', 'B', 'C'); voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); voidPromise = element.submit(); - element.getId().then(function (id: typeof webdriver.WebElement.Id) { }); + element.getId().then(function (id: string) { }); element.getRawId().then(function (id: string) { }); - element.serialize().then(function (id: typeof webdriver.WebElement.Id) { }); + element.serialize().then(function (id: webdriver.IWebElementId) { }); - booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, { ELEMENT: 'ID2' })); - - var id: typeof webdriver.WebElement.Id = webdriver.WebElement.Id; - var key: string = webdriver.WebElement.ELEMENT_KEY; + booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); } function TestWebElementPromise() { @@ -877,7 +839,7 @@ function TestLogging() { preferences.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.ALL); var prefs: any = preferences.toJSON(); - var level: webdriver.logging.ILevel = webdriver.logging.getLevel('OFF'); + var level: webdriver.logging.Level = webdriver.logging.getLevel('OFF'); level = webdriver.logging.getLevel(1); level = webdriver.logging.Level.ALL; @@ -887,10 +849,10 @@ function TestLogging() { level = webdriver.logging.Level.SEVERE; level = webdriver.logging.Level.WARNING; - var name: string = level.name; - var value: number = level.value; + var name: string = level.name(); + var value: number = level.value(); - var type: string; + var type: webdriver.logging.Type; type = webdriver.logging.Type.BROWSER; type = webdriver.logging.Type.CLIENT; type = webdriver.logging.Type.DRIVER; @@ -913,9 +875,6 @@ function TestLoggingEntry() { var message: string = entry.message; var timestamp: number = entry.timestamp; var type: string = entry.type; - - entry = webdriver.logging.Entry.fromClosureLogRecord({}); - entry = webdriver.logging.Entry.fromClosureLogRecord({}, webdriver.logging.Type.DRIVER); } function TestPromiseModule() { @@ -946,29 +905,29 @@ function TestPromiseModule() { return 5; }, this, 1, 2, 3).then(function (value: number) { }); - var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (el: number, index: number, arr: 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 (el: number, index: number, arr: number[]) { + 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 (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { + 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, index: number, arr: number[]) { + 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, index: number, arr: number[]) { + 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, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { return true; }, this); @@ -995,26 +954,13 @@ function TestPromiseModule() { var bool: boolean = webdriver.promise.isGenerator(function () { }); var isPromise: boolean = webdriver.promise.isPromise('ABC'); - voidPromise = webdriver.promise.rejected({a: 123}); + 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 TestStacktraceModule() { - var bool: boolean = webdriver.stacktrace.BROWSER_SUPPORTED; - - var frame: webdriver.stacktrace.Frame = new webdriver.stacktrace.Frame(); - var baseFrame: webdriver.stacktrace.Frame = frame; - - var snapshot: webdriver.stacktrace.Snapshot = new webdriver.stacktrace.Snapshot(); - var baseSnapshot: webdriver.stacktrace.Snapshot = snapshot; - - var err: Error = webdriver.stacktrace.format(new Error("Error")); - var frames: webdriver.stacktrace.Frame[] = webdriver.stacktrace.get(); -} - function TestUntilModule() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). @@ -1125,13 +1071,12 @@ function TestPromiseClass() { } function TestThenableClass() { - var thenable: webdriver.promise.Thenable = new webdriver.promise.Thenable(); + var thenable: webdriver.promise.Promise = new webdriver.promise.Promise(); thenable.cancel('Abort'); var isPending: boolean = thenable.isPending(); - thenable = thenable.then(); 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; }); @@ -1144,76 +1089,30 @@ function TestThenableClass() { function TestErrorCode() { var errorCode: number; - errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE; - errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_VISIBLE; - errorCode = webdriver.error.ErrorCode.IME_ENGINE_ACTIVATION_FAILED; - errorCode = webdriver.error.ErrorCode.IME_NOT_AVAILABLE; - errorCode = webdriver.error.ErrorCode.INVALID_COOKIE_DOMAIN; - errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_COORDINATES; - errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_STATE; - errorCode = webdriver.error.ErrorCode.INVALID_SELECTOR_ERROR; - errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR; - errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPE; - errorCode = webdriver.error.ErrorCode.JAVASCRIPT_ERROR; - errorCode = webdriver.error.ErrorCode.METHOD_NOT_ALLOWED; - errorCode = webdriver.error.ErrorCode.MODAL_DIALOG_OPENED; - errorCode = webdriver.error.ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS; - errorCode = webdriver.error.ErrorCode.NO_MODAL_DIALOG_OPEN; - errorCode = webdriver.error.ErrorCode.NO_SUCH_ELEMENT; - errorCode = webdriver.error.ErrorCode.NO_SUCH_FRAME; - errorCode = webdriver.error.ErrorCode.NO_SUCH_WINDOW; - errorCode = webdriver.error.ErrorCode.SCRIPT_TIMEOUT; - errorCode = webdriver.error.ErrorCode.SESSION_NOT_CREATED; - errorCode = webdriver.error.ErrorCode.SQL_DATABASE_ERROR; - errorCode = webdriver.error.ErrorCode.STALE_ELEMENT_REFERENCE; - errorCode = webdriver.error.ErrorCode.SUCCESS; - errorCode = webdriver.error.ErrorCode.TIMEOUT; - errorCode = webdriver.error.ErrorCode.UNABLE_TO_SET_COOKIE; - errorCode = webdriver.error.ErrorCode.UNKNOWN_COMMAND; - errorCode = webdriver.error.ErrorCode.UNKNOWN_ERROR; - errorCode = webdriver.error.ErrorCode.UNSUPPORTED_OPERATION; - errorCode = webdriver.error.ErrorCode.XPATH_LOOKUP_ERROR; -} - -function TestError() { - var error: webdriver.error.Error; - - error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE); - error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE, 'Message'); - - var code: number = error.code; - var state: string = error.state; - var message: string = error.message; - var name: string = error.name; - var stack: string = error.stack; - var isAutomationError: boolean = error.isAutomationError; - var errorStr: string = error.toString(); - - state = webdriver.error.Error.State.ELEMENT_NOT_SELECTABLE - state = webdriver.error.Error.State.ELEMENT_NOT_VISIBLE; - state = webdriver.error.Error.State.IME_ENGINE_ACTIVATION_FAILED; - state = webdriver.error.Error.State.IME_NOT_AVAILABLE; - state = webdriver.error.Error.State.INVALID_COOKIE_DOMAIN; - state = webdriver.error.Error.State.INVALID_ELEMENT_COORDINATES; - state = webdriver.error.Error.State.INVALID_ELEMENT_STATE; - state = webdriver.error.Error.State.INVALID_SELECTOR; - state = webdriver.error.Error.State.JAVASCRIPT_ERROR; - state = webdriver.error.Error.State.MOVE_TARGET_OUT_OF_BOUNDS; - state = webdriver.error.Error.State.NO_SUCH_ALERT; - state = webdriver.error.Error.State.NO_SUCH_DOM - state = webdriver.error.Error.State.NO_SUCH_ELEMENT; - state = webdriver.error.Error.State.NO_SUCH_FRAME; - state = webdriver.error.Error.State.NO_SUCH_WINDOW; - state = webdriver.error.Error.State.SCRIPT_TIMEOUT; - state = webdriver.error.Error.State.SESSION_NOT_CREATED; - state = webdriver.error.Error.State.STALE_ELEMENT_REFERENCE; - state = webdriver.error.Error.State.SUCCESS; - state = webdriver.error.Error.State.TIMEOUT; - state = webdriver.error.Error.State.UNABLE_TO_SET_COOKIE; - state = webdriver.error.Error.State.UNEXPECTED_ALERT_OPEN - state = webdriver.error.Error.State.UNKNOWN_COMMAND; - state = webdriver.error.Error.State.UNKNOWN_ERROR; - state = webdriver.error.Error.State.UNSUPPORTED_OPERATION; + 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() { diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 548048b695..b3afe098ac 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1,5 +1,5 @@ -// Type definitions for Selenium WebDriverJS 2.44.0 -// Project: https://code.google.com/p/selenium/ +// 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 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -19,8 +19,7 @@ declare namespace chrome { * {@code null} to use the currently active flow. * @constructor */ - constructor(opt_config?: webdriver.Capabilities, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); - constructor(opt_config?: Options, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: Options|webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); } interface IOptionsValues { @@ -240,6 +239,53 @@ declare namespace chrome { 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. @@ -255,21 +301,6 @@ declare namespace chrome { * @return {!webdriver.Capabilities} The capabilities. */ toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; - - - /** - * Converts this instance to its JSON wire protocol representation. Note this - * function is an implementation not intended for general use. - * @return {{args: !Array., - * binary: (string|undefined), - * detach: boolean, - * extensions: !Array., - * localState: (Object|undefined), - * logFile: (string|undefined), - * prefs: (Object|undefined)}} The JSON wire protocol representation - * of this instance. - */ - toJSON(): IOptionsValues; } /** @@ -348,8 +379,7 @@ declare namespace chrome { * configuration to use. * @return {!ServiceBuilder} A self reference. */ - setStdio(config: string): ServiceBuilder; - setStdio(config: any[]): ServiceBuilder; + setStdio(config: string|Array): ServiceBuilder; /** @@ -368,7 +398,7 @@ declare namespace chrome { * @throws {Error} If the driver exectuable was not specified and a default * could not be found on the current PATH. */ - build(): any; + build(): remote.DriverService; } /** @@ -377,395 +407,1325 @@ declare namespace chrome { * a ChromeDriver executable found on the system PATH. * @return {!remote.DriverService} The default ChromeDriver service. */ - function getDefaultService(): any; + 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: any): void; + function setDefaultService(service: remote.DriverService): void; } -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); +declare namespace edge { - /** - * 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; - } - - /** - * A WebDriver client for Firefox. - * - * @extends {webdriver.WebDriver} - */ class Driver extends webdriver.WebDriver { - /** - * @param {(Options|webdriver.Capabilities|Object)=} opt_config The - * configuration options for this driver, specified as either an - * {@link Options} or {@link webdriver.Capabilities}, or as a raw hash - * object. - * @param {webdriver.promise.ControlFlow=} opt_flow The flow to - * schedule commands through. Defaults to the active flow object. - * @constructor - */ - constructor(opt_config?: webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); - constructor(opt_config?: any, opt_flow?: webdriver.promise.ControlFlow); + /** + * @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; } /** - * Configuration options for the FirefoxDriver. + * Class for managing MicrosoftEdgeDriver specific options. */ class Options { - /** - * @constructor - */ - constructor(); - /** - * 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): Options; - setProfile(profile: Profile): 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 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): Options; - setBinary(binary: Binary): 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; - - /** - * Sets the logging preferences for the new session. - * @param {webdriver.logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; - - - /** - * Sets the proxy to use. - * - * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - - /** - * Converts these options to a {@link webdriver.Capabilities} instance. - * - * @return {!webdriver.Capabilities} A new capabilities object. - */ - toCapabilities(opt_remote?: any): webdriver.Capabilities; + /** + * 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; } /** - * Models a Firefox proifle directory for use with the FirefoxDriver. The - * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} - * is called. + * Creates {@link remote.DriverService} instances that manage a + * MicrosoftEdgeDriver server in a child process. */ - 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); + 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); - /** - * 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; + /** + * 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; - /** - * 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; + /** + * 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; - - /** - * 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; + /** + * 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 url The server's URL, or a promise that will resolve to that URL. - * @returns {!webdriver.CommandExecutor} The new command executor. + * @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.CommandExecutor; - function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; + 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 { - interface IErrorCode { - SUCCESS: number; + class IError extends Error { + constructor(opt_error?: string); - NO_SUCH_ELEMENT: number; - NO_SUCH_FRAME: number; - UNKNOWN_COMMAND: number; - UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. - STALE_ELEMENT_REFERENCE: number; - ELEMENT_NOT_VISIBLE: number; - INVALID_ELEMENT_STATE: number; - UNKNOWN_ERROR: number; - ELEMENT_NOT_SELECTABLE: number; - JAVASCRIPT_ERROR: number; - XPATH_LOOKUP_ERROR: number; - TIMEOUT: number; - NO_SUCH_WINDOW: number; - INVALID_COOKIE_DOMAIN: number; - UNABLE_TO_SET_COOKIE: number; - MODAL_DIALOG_OPENED: number; - UNEXPECTED_ALERT_OPEN: number; - NO_SUCH_ALERT: number; - NO_MODAL_DIALOG_OPEN: number; - SCRIPT_TIMEOUT: number; - INVALID_ELEMENT_COORDINATES: number; - IME_NOT_AVAILABLE: number; - IME_ENGINE_ACTIVATION_FAILED: number; - INVALID_SELECTOR_ERROR: number; - SESSION_NOT_CREATED: number; - MOVE_TARGET_OUT_OF_BOUNDS: number; - SQL_DATABASE_ERROR: number; - INVALID_XPATH_SELECTOR: number; - INVALID_XPATH_SELECTOR_RETURN_TYPE: number; - // The following error codes are derived straight from HTTP return codes. - METHOD_NOT_ALLOWED: number; + code(): number; } - var ErrorCode: IErrorCode; + /** + * 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); + } /** - * Error extension that includes error status codes from the WebDriver wire - * protocol: - * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes - * - * @extends {Error} + * An attempt was made to select an element that cannot be selected. */ - class Error { + class ElementNotSelectableError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Constructors + /** + * 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); + } - /** - * @param {!bot.ErrorCode} code The error's status code. - * @param {string=} opt_message Optional error message. - * @constructor - */ - constructor(code: number, opt_message?: 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); + } - //endregion + /** + * 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); + } - //region Static Properties + /** + * 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); + } - /** - * Status strings enumerated in the W3C WebDriver working draft. - * @enum {string} - * @see http://www.w3.org/TR/webdriver/#status-codes - */ - static State: { - ELEMENT_NOT_SELECTABLE: string; - ELEMENT_NOT_VISIBLE: string; - IME_ENGINE_ACTIVATION_FAILED: string; - IME_NOT_AVAILABLE: string; - INVALID_COOKIE_DOMAIN: string; - INVALID_ELEMENT_COORDINATES: string; - INVALID_ELEMENT_STATE: string; - INVALID_SELECTOR: string; - JAVASCRIPT_ERROR: string; - MOVE_TARGET_OUT_OF_BOUNDS: string; - NO_SUCH_ALERT: string; - NO_SUCH_DOM: string; - NO_SUCH_ELEMENT: string; - NO_SUCH_FRAME: string; - NO_SUCH_WINDOW: string; - SCRIPT_TIMEOUT: string; - SESSION_NOT_CREATED: string; - STALE_ELEMENT_REFERENCE: string; - SUCCESS: string; - TIMEOUT: string; - UNABLE_TO_SET_COOKIE: string; - UNEXPECTED_ALERT_OPEN: string; - UNKNOWN_COMMAND: string; - UNKNOWN_ERROR: string; - UNSUPPORTED_OPERATION: 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); + } - //endregion + /** + * Argument was an invalid selector. + */ + class InvalidSelectorError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Properties + /** + * 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); + } - /** - * This error's status code. - * @type {!bot.ErrorCode} - */ - code: number; + /** + * 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); + } - /** @type {string} */ - state: 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); + } - /** @override */ - message: 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); + } - /** @override */ - name: 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); + } - /** @override */ - stack: 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); + } - /** - * Flag used for duck-typing when this code is embedded in a Firefox extension. - * This is required since an Error thrown in one component and then reported - * to another will fail instanceof checks in the second component. - * @type {boolean} - */ - isAutomationError: boolean; + /** + * 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); + } - //endregion + /** + * 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); + } - //region Methods + /** + * A new session could not be created. + */ + class SessionNotCreatedError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @return {string} The string representation of this error. */ - toString(): 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); + } - //endregion + /** + * 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); } } @@ -776,48 +1736,96 @@ declare namespace webdriver { * @typedef {Object.} */ class Preferences { - setLevel(type: string, level: ILevel): void; + setLevel(type: string|Type, level: Level|string|number): void; toJSON(): { [key: string]: string }; } - interface IType { - /** Logs originating from the browser. */ - BROWSER: string; - /** Logs from a WebDriver client. */ - CLIENT: string; - /** Logs from a WebDriver implementation. */ - DRIVER: string; - /** Logs related to performance. */ - PERFORMANCE: string; - /** Logs from the remote server. */ - SERVER: string; - } - /** * Common log types. * @enum {string} */ - var Type: IType; + 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 + } /** - * Logging levels. - * @enum {{value: number, name: webdriver.logging.LevelName}} + * Defines a message level that may be used to control logging output. + * + * @final */ - interface ILevel { - value: number; - name: string; - } + 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); - interface ILevelValues { - ALL: ILevel; - DEBUG: ILevel; - INFO: ILevel; - WARNING: ILevel; - SEVERE: ILevel; - OFF: ILevel; - } + /** @override */ + toString(): string; - var Level: ILevelValues; + /** 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. @@ -827,75 +1835,209 @@ declare namespace webdriver { * convert . * @return {!webdriver.logging.Level} The converted level. */ - function getLevel(nameOrValue: string): ILevel; - function getLevel(nameOrValue: number): ILevel; + function getLevel(nameOrValue: string|number): Level; interface IEntryJSON { - level: string; - message: string; - timestamp: number; - type: string; + 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); - //region Constructors + /** @type {!webdriver.logging.Level} */ + level: Level; - /** - * @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: ILevel, message: string, opt_timestamp?:number, opt_type?:string); - constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); + /** @type {string} */ + message: string; - //endregion + /** @type {number} */ + timestamp: number; - //region Public Properties + /** @type {string} */ + type: string; - /** @type {!webdriver.logging.Level} */ - level: ILevel; + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + } - /** @type {string} */ - message: string; + /** + * 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); - /** @type {number} */ - timestamp: number; + /** @private {string} */ + name_: string; + /** @private {Level} */ + level_: Level; + /** @private {Logger} */ + parent_: Logger; + /** @private {Set} */ + handlers_: any; - /** @type {string} */ - type: string; + /** @return {string} the name of this logger. */ + getName(): string; - //endregion + /** + * @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; - //region Static Methods + /** @return {Level} the log level for this logger. */ + getLevel(): Level; - /** - * Converts a {@link goog.debug.LogRecord} into a - * {@link webdriver.logging.Entry}. - * @param {!goog.debug.LogRecord} logRecord The record to convert. - * @param {string=} opt_type The log type. - * @return {!webdriver.logging.Entry} The converted entry. - */ - static fromClosureLogRecord(logRecord: any, opt_type?:string): Entry; + /** + * @return {!Level} the effective level for this logger. + */ + getEffectiveLevel(): Level; - //endregion + /** + * @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; - //region Methods + /** + * 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; - /** - * @return {{level: string, message: string, timestamp: number, - * type: string}} The JSON representation of this entry. - */ - toJSON(): IEntryJSON; + /** + * 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; - //endregion + /** + * 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; } } @@ -908,15 +2050,15 @@ declare namespace webdriver { * input array's promises are rejected, the returned promise will be rejected * with the same reason. * - * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of + * @param {!Array<(T|!ManagedPromise)>} arr An array of * promises to wait on. - * @return {!webdriver.promise.Promise.>} A promise that is + * @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: Promise[]): Promise; + function all(arr: Array>): Promise; /** * Invokes the appropriate callback function as soon as a promised @@ -939,9 +2081,9 @@ declare namespace webdriver { * 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(!webdriver.promise.ControlFlow)} callback The entry point + * @param {function(!ControlFlow)} callback The entry point * to the newly created flow. - * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * @return {!ManagedPromise} A promise that resolves to the callback * result. */ function createFlow(callback: (flow: ControlFlow) => R): Promise; @@ -966,7 +2108,7 @@ declare namespace webdriver { * 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 {!webdriver.promise.Promise} The promise. + * @return {!ManagedPromise} The promise. */ function delayed(ms: number): Promise; @@ -974,26 +2116,25 @@ declare namespace webdriver { * 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 + * 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 + * 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.|webdriver.promise.Promise.>)} arr The + * @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|webdriver.promise.Promise.)} fn The function + * @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: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise; - function filter(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function filter(arr: Array|Promise>, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; /** * Creates a new deferred object. @@ -1003,8 +2144,9 @@ declare namespace webdriver { /** * Creates a promise that has been resolved with the given value. - * @param {*=} opt_value The resolved value. - * @return {!webdriver.promise.Promise} The resolved promise. + * @param {T=} opt_value The resolved value. + * @return {!ManagedPromise} The resolved promise. + * @template T */ function fulfilled(opt_value?: T): Promise; @@ -1013,42 +2155,44 @@ declare namespace webdriver { * 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 + * 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 + * 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.|webdriver.promise.Promise.>)} arr The + * @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 + * @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: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise - function map(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + 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 {!webdriver.promise.Promise} The rejected promise. + * @return {!ManagedPromise} The rejected promise. + * @template T */ - function rejected(opt_reason?: any): Promise; + function rejected(opt_reason?: any): Promise; /** - * Wraps a function that is assumed to be a node-style callback as its final - * argument. This callback takes two arguments: an error value (which will be + * 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. - * If the call fails, the returned promise will be rejected, otherwise it will - * be resolved with the result. + * The callback will the resolve or reject the returned promise, based on its + * arguments. * @param {!Function} fn The function to wrap. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * @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; @@ -1059,37 +2203,35 @@ declare namespace webdriver { * 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. - *

    
    -         * webdriver.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 1:__ the Fibonacci Sequence. * - *

    Example 2: a generator that throws. - *

    
    -         * webdriver.promise.consume(function* () {
    -         *   yield webdriver.promise.delayed(250).then(function() {
    -         *     throw Error('boom');
    -         *   });
    -         * }).thenCatch(function(e) {
    -         *   console.log(e.toString());  // Error: boom
    -         * });
    -         * 
    + * 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 {!webdriver.promise.Promise.} A promise that will resolve to the + * @return {!ManagedPromise} A promise that will resolve to the * generator's final result. * @throws {TypeError} If the given function is not a generator. */ @@ -1104,10 +2246,9 @@ declare namespace webdriver { * resolved successfully. * @param {Function=} opt_errback The function to call when the value is * rejected. - * @return {!webdriver.promise.Promise} A new promise. + * @return {!ManagedPromise} A new promise. */ - function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; - function when(value: Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): 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 @@ -1120,19 +2261,19 @@ declare namespace webdriver { * Warning: This function makes no checks against objects that contain * cyclical references: * - * var value = {}; - * value['self'] = value; - * webdriver.promise.fullyResolved(value); // Stack overflow. + * var value = {}; + * value['self'] = value; + * promise.fullyResolved(value); // Stack overflow. * * @param {*} value The value to fully resolve. - * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * @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 {!webdriver.promise.ControlFlow} flow The new default flow. + * @param {!ControlFlow} flow The new default flow. * @throws {Error} If the default flow is not currently active. */ function setDefaultFlow(flow: ControlFlow): void; @@ -1141,265 +2282,181 @@ declare namespace webdriver { /** * Error used when the computation of a promise is cancelled. - * - * @extends {goog.debug.Error} - * @final */ - class CancellationError { - /** - * @param {string=} opt_msg The cancellation message. - * @constructor - */ - constructor(opt_msg?: string); - - name: string; - message: string; + 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 alreayd been resolved. + * 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=} opt_reason The reason this promise is being cancelled. + * @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): void; - + 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 opt_callback The + * @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 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 + * @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) => Promise, opt_errback?: (error: any) => any): 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: T) => R, opt_errback?: (error: any) => any): Promise; - + 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().thenCatch(function(ex) {
    -             *     console.error(ex);
    -             *   });
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (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 + * // 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 */ - thenCatch(errback: (error: any) => any): 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): Promise; + 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 - */ + * 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 alreayd been resolved. + * 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=} opt_reason The reason this promise is being cancelled. + * @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): void; - + 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 opt_callback The + * @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 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 + * @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) => Promise, opt_errback?: (error: any) => any): 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: T) => R, opt_errback?: (error: any) => any): Promise; - + 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().thenCatch(function(ex) {
    -             *     console.error(ex);
    -             *   });
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (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 + * // 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 */ - thenCatch(errback: (error: any) => any): Promise; - + 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);
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } finally { + * cleanUp(); + * } * - * Note: similar to the {@code finally} clause, if the registered + * // 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
    -             *   }
                  *
    -             *   webdriver.promise.rejected(Error('one'))
    -             *       .thenFinally(function() {
    -             *         throw Error('two');  // Hides Error: one
    -             *       });
    -             * 
    + * 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|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * @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 */ - thenFinally(callback: () => any): Promise; + 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: webdriver.promise.Thenable, ...[?])} ctor The + * 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 webdriver.promise.Thenable.addImplementation}. + * 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. @@ -1432,12 +2489,11 @@ declare namespace webdriver { * 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 {promise.ControlFlow=} opt_flow The control flow + * 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 - */ + */ constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); constructor(); // For angular-protractor/angular-protractor-tests.ts @@ -1450,7 +2506,7 @@ declare namespace webdriver { * {@code Error}, one will be created using the value's string * representation. */ - cancel(reason: any): void; + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; @@ -1468,23 +2524,7 @@ declare namespace webdriver { * @return A new promise which will be resolved * with the result of the invoked callback. */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * 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?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: Function, opt_errback?: Function): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous @@ -1512,6 +2552,31 @@ declare namespace webdriver { */ 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 @@ -1552,7 +2617,7 @@ declare namespace webdriver { * with the callback result. * @template R */ - thenFinally(callback: () => any): Promise; + thenFinally(callback: Function): Promise; //endregion } @@ -1791,107 +2856,6 @@ declare namespace webdriver { } } - namespace stacktrace { - /** - * Class representing one stack frame. - */ - class Frame { - /** - * @param {(string|undefined)} context Context object, empty in case of global - * functions or if the browser doesn't provide this information. - * @param {(string|undefined)} name Function name, empty in case of anonymous - * functions. - * @param {(string|undefined)} alias Alias of the function if available. For - * example the function name will be 'c' and the alias will be 'b' if the - * function is defined as a.b = function c() {};. - * @param {(string|undefined)} path File path or URL including line number and - * optionally column number separated by colons. - * @constructor - */ - constructor(context?: string, name?: string, alias?: string, path?: string); - - /** - * @return {string} The function name or empty string if the function is - * anonymous and the object field which it's assigned to is unknown. - */ - getName(): string; - - - /** - * @return {string} The url or empty string if it is unknown. - */ - getUrl(): string; - - - /** - * @return {number} The line number if known or -1 if it is unknown. - */ - getLine(): number; - - - /** - * @return {number} The column number if known and -1 if it is unknown. - */ - getColumn(): number; - - - /** - * @return {boolean} Whether the stack frame contains an anonymous function. - */ - isAnonymous(): boolean; - - - /** - * Converts this frame to its string representation using V8's stack trace - * format: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi - * @return {string} The string representation of this frame. - * @override - */ - toString(): string; - } - - /** - * Stores a snapshot of the stack trace at the time this instance was created. - * The stack trace will always be adjusted to exclude this function call. - */ - class Snapshot { - /** - * @param {number=} opt_slice The number of frames to remove from the top of - * the generated stack trace. - * @constructor - */ - constructor(opt_slice?: number); - - /** - * @return {!Array.} The parsed stack trace. - */ - getStacktrace(): Frame[]; - } - - /** - * Formats an error's stack trace. - * @param {!(Error|goog.testing.JsUnitException)} error The error to format. - * @return {!(Error|goog.testing.JsUnitException)} The formatted error. - */ - function format(error: any): any; - - /** - * Gets the native stack trace if available otherwise follows the call chain. - * The generated trace will exclude all frames up to and including the call to - * this function. - * @return {!Array.} The frames of the stack trace. - */ - function get(): Frame[]; - - /** - * Whether the current browser supports stack traces. - * - * @type {boolean} - * @const - */ - var BROWSER_SUPPORTED: boolean; - } - namespace until { /** * Defines a condition to @@ -1915,32 +2879,31 @@ declare namespace webdriver { /** * 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 {@code 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. - *
    + * to the designated frame. The target frame may be specified as * - *

    Upon successful resolution of this condition, the driver will be left + * 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| - * webdriver.Locator|webdriver.By.Hash| - * function(!webdriver.WebDriver): !webdriver.WebElement)} frame + * @param {!(number|./webdriver.WebElement|By| + * function(!./webdriver.WebDriver): !./webdriver.WebElement)} frame * The frame identifier. - * @return {!until.Condition.} A new condition. + * @return {!Condition} A new condition. */ - function ableToSwitchToFrame(frame: number|WebElement|Locator|By.Hash|((webdriver: WebDriver)=>WebElement)): 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 {!until.Condition.} The new condition. + * @return {!Condition} The new condition. */ function alertIsPresent(): Condition; @@ -2000,13 +2963,12 @@ declare namespace webdriver { /** * Creates a condition that will loop until an element is - * {@link webdriver.WebDriver#findElement found} with the given locator. + * {@link ./webdriver.WebDriver#findElement found} with the given locator. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. + * @param {!(By|Function)} locator The locator to use. * @return {!until.Condition.} The new condition. */ - function elementLocated(locator: Locator|By.Hash|Function): Condition; + function elementLocated(locator: By|Function): Condition; /** * Creates a condition that will wait for the given element's @@ -2039,7 +3001,7 @@ declare namespace webdriver { * * @param {!webdriver.WebElement} element The element to test. * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. * @see webdriver.WebDriver#getText */ function elementTextMatches(element: WebElement, regex: RegExp): Condition; @@ -2053,7 +3015,7 @@ declare namespace webdriver { * @return {!until.Condition.>} The new * condition. */ - function elementsLocated(locator: Locator|By.Hash|Function): Condition; + function elementsLocated(locator: By|Function): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -2061,7 +3023,7 @@ declare namespace webdriver { * has loaded. * * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. */ function stalenessOf(element: WebElement): Condition; @@ -2080,7 +3042,7 @@ declare namespace webdriver { * given value. * * @param {string} title The expected page title. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. */ function titleIs(title: string): Condition; @@ -2105,18 +3067,18 @@ declare namespace webdriver { } /** - * Enumeration of the buttons used in the advanced interactions API. - * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. - * @enum {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} */ - interface IButton { - LEFT: number; - MIDDLE: number; - RIGHT: number; + enum Button { + LEFT, + MIDDLE, + RIGHT, } - var Button: IButton; - /** * Representations of pressable keys that aren't text. These are stored in * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to @@ -2124,102 +3086,86 @@ declare namespace webdriver { * * @enum {string} */ - interface IKey { - NULL: string; - CANCEL: string; // ^break - HELP: string; - BACK_SPACE: string; - TAB: string; - CLEAR: string; - RETURN: string; - ENTER: string; - SHIFT: string; - CONTROL: string; - ALT: string; - PAUSE: string; - ESCAPE: string; - SPACE: string; - PAGE_UP: string; - PAGE_DOWN: string; - END: string; - HOME: string; - ARROW_LEFT: string; - LEFT: string; - ARROW_UP: string; - UP: string; - ARROW_RIGHT: string; - RIGHT: string; - ARROW_DOWN: string; - DOWN: string; - INSERT: string; - DELETE: string; - SEMICOLON: string; - EQUALS: 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: string; // number pad keys - NUMPAD1: string; - NUMPAD2: string; - NUMPAD3: string; - NUMPAD4: string; - NUMPAD5: string; - NUMPAD6: string; - NUMPAD7: string; - NUMPAD8: string; - NUMPAD9: string; - MULTIPLY: string; - ADD: string; - SEPARATOR: string; - SUBTRACT: string; - DECIMAL: string; - DIVIDE: string; + NUMPAD0, // number pad keys + NUMPAD1, + NUMPAD2, + NUMPAD3, + NUMPAD4, + NUMPAD5, + NUMPAD6, + NUMPAD7, + NUMPAD8, + NUMPAD9, + MULTIPLY, + ADD, + SEPARATOR, + SUBTRACT, + DECIMAL, + DIVIDE, - F1: string; // function keys - F2: string; - F3: string; - F4: string; - F5: string; - F6: string; - F7: string; - F8: string; - F9: string; - F10: string; - F11: string; - F12: string; + F1, // function keys + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, - COMMAND: string; // Apple command key - META: string; // alias for Windows key + COMMAND, // Apple command key + META // alias for Windows key - /** - * Simulate pressing many keys at once in a "chord". Takes a sequence of - * {@link webdriver.Key}s or strings, appends each of the values to a string, - * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns - * the resultant string. - * - * Note: when the low-level webdriver key handlers see Keys.NULL, active - * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. - * - * @param {...string} var_args The key sequence to concatenate. - * @return {string} The null-terminated key sequence. - * @see http://code.google.com/p/webdriver/issues/detail?id=79 - */ - chord: (...var_args: string[]) => string; } - var Key: IKey; - /** * Class for defining sequences of complex user interactions. Each sequence * will not be executed until {@link #perform} is called. * - *

    Example:

    
    -     *   new webdriver.ActionSequence(driver).
    -     *       keyDown(webdriver.Key.SHIFT).
    -     *       click(element1).
    -     *       click(element2).
    -     *       dragAndDrop(element3, element4).
    -     *       keyUp(webdriver.Key.SHIFT).
    -     *       perform();
    -     * 
    + * Example: + * + * new ActionSequence(driver). + * keyDown(Key.SHIFT). + * click(element1). + * click(element2). + * dragAndDrop(element3, element4). + * keyUp(Key.SHIFT). + * perform(); * */ class ActionSequence { @@ -2247,14 +3193,18 @@ declare namespace webdriver { * 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 An optional offset, in pixels. - * Defaults to (0, 0). - * @return {!webdriver.ActionSequence} A self reference. + * + * @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, opt_offset?: ILocation): ActionSequence; - mouseMove(location: ILocation): ActionSequence; + mouseMove(location: WebElement|ILocation, opt_offset?: ILocation): ActionSequence; /** * Presses a mouse button. The mouse button will not be released until @@ -2262,100 +3212,101 @@ declare namespace webdriver { * 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 + * 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 - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).mouseDown() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * 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 webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @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 {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - mouseDown(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - mouseDown(opt_elementOrButton?: number): ActionSequence; + 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 + * 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 - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).mouseUp() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * 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 webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @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 {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - mouseUp(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - mouseUp(opt_elementOrButton?: number): ActionSequence; + 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 {!webdriver.ActionSequence} A self reference. + * + * @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): ActionSequence; - dragAndDrop(element: WebElement, location: ILocation): ActionSequence; + 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 + * 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|webdriver.Button)=} opt_elementOrButton Either + * 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 webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @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 {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - click(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - click(opt_elementOrButton?: number): ActionSequence; + 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 + * 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 - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).doubleClick() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * 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 webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @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 {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - doubleClick(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - doubleClick(opt_elementOrButton?: number): ActionSequence; + doubleClick(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Performs a modifier key press. The modifier key is not released @@ -2366,7 +3317,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyDown(key: string): ActionSequence; + keyDown(key: Key): ActionSequence; /** * Performs a modifier key release. The release is targetted at the currently @@ -2376,7 +3327,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyUp(key: string): ActionSequence; + keyUp(key: Key): ActionSequence; /** * Simulates typing multiple keys. Each modifier key encountered in the @@ -2387,7 +3338,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - sendKeys(...var_args: any[]): ActionSequence; + sendKeys(...var_args: Array): ActionSequence; //endregion } @@ -2483,7 +3434,6 @@ declare namespace webdriver { */ scroll(offset: IOffset): TouchSequence; - /** * Scrolls the touch screen, starting on `elem` and moving by the specified * offset. @@ -2494,7 +3444,6 @@ declare namespace webdriver { */ scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; - /** * Flick, starting anywhere on the screen, at speed xspeed and yspeed. * @@ -2504,7 +3453,6 @@ declare namespace webdriver { */ flick(speed: ISpeed): TouchSequence; - /** * Flick starting at elem and moving by x and y at specified speed. * @@ -2516,26 +3464,29 @@ declare namespace webdriver { 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}). */ - interface Alert { + 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 @@ -2547,6 +3498,18 @@ declare namespace webdriver { */ 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 @@ -2580,47 +3543,27 @@ declare namespace webdriver { * 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();
          *     });
    -     * 
    * - * @param {!webdriver.WebDriver} driver The driver controlling the browser this - * alert is attached to. - * @param {!webdriver.promise.Thenable.} alert A thenable - * that will be fulfilled with the promised alert. - * @constructor - * @extends {webdriver.Alert} - * @implements {webdriver.promise.Thenable.} + * @implements {promise.Thenable.} * @final */ - interface AlertPromise extends Alert, webdriver.promise.IThenable { + 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); } - /** - * An error returned to indicate that there is an unhandled modal dialog on the - * current page. - * @extends {bot.Error} - */ - interface UnhandledAlertError extends webdriver.error.Error { - //region Methods - - /** - * @return {string} The text displayed with the unhandled alert. - */ - getAlertText(): string; - - /** - * @return {!webdriver.Alert} The open alert. - * @deprecated Use {@link #getAlertText}. This method will be removed in - * 2.45.0. - */ - getAlert(): Alert; - - - //endregion + /** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ + class UnhandledAlertError extends webdriver.error.UnexpectedAlertOpenError { } /** @@ -2630,7 +3573,9 @@ declare namespace webdriver { interface IBrowser { ANDROID: string; CHROME: string; + EDGE: string; FIREFOX: string; + IE: string; INTERNET_EXPLORER: string; IPAD: string; IPHONE: string; @@ -2651,6 +3596,45 @@ declare namespace webdriver { 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 @@ -2664,15 +3648,45 @@ declare namespace webdriver { //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 @@ -2705,6 +3719,12 @@ declare namespace webdriver { */ 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. @@ -2735,6 +3755,17 @@ declare namespace webdriver { */ 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. @@ -2753,6 +3784,16 @@ declare namespace webdriver { */ 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}. @@ -2760,17 +3801,37 @@ declare namespace webdriver { * desired logging preferences. * @return {!Builder} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Builder; - setLoggingPrefs(prefs: { [key: string]: string }): Builder; + 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 {!webdriver.ProxyConfig} config The configuration to use. + * @param {!capabilities.ProxyConfig} config The configuration to use. * @return {!Builder} A self reference. */ - setProxy(config: ProxyConfig): Builder; + 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. @@ -2793,6 +3854,16 @@ declare namespace webdriver { */ 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. @@ -2800,12 +3871,149 @@ declare namespace webdriver { * capabilities for a new session. * @return {!Builder} A self reference. */ - withCapabilities(capabilities: Capabilities): Builder; - withCapabilities(capabilities: any): Builder; + 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} @@ -2876,7 +4084,7 @@ declare namespace webdriver { SECURE_SSL: string; /** Whether the driver supports manipulating the app cache. */ - SUPPORTS_APPLICATION_CACHE: string; + SUPPORTS_APPLICATION_CACHE: string; /** Whether the driver supports locating elements with CSS selectors. */ SUPPORTS_CSS_SELECTORS: string; @@ -2910,8 +4118,7 @@ declare namespace webdriver { * capabilities to merge into this instance. * @constructor */ - constructor(opt_other?: Capabilities); - constructor(opt_other?: any); + constructor(opt_other?: Capabilities|Object); //endregion @@ -2927,8 +4134,7 @@ declare namespace webdriver { * merge into this instance. * @return {!webdriver.Capabilities} A self reference. */ - merge(other: Capabilities): Capabilities; - merge(other: any): Capabilities; + merge(other: Capabilities|Object): Capabilities; /** * @param {string} key The capability to set. @@ -2946,9 +4152,7 @@ declare namespace webdriver { * logging preferences. * @return {!webdriver.Capabilities} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Capabilities; - setLoggingPrefs(prefs: { [key: string]: string }): Capabilities; - + setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Capabilities; /** * Sets the proxy configuration for this instance. @@ -3010,6 +4214,11 @@ declare namespace webdriver { */ 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. */ @@ -3183,6 +4392,8 @@ declare namespace webdriver { GET_AVAILABLE_LOG_TYPES: string; GET_LOG: string; GET_SESSION_LOGS: string; + + UPLOAD_FILE: string; } var CommandName: ICommandName; @@ -3241,19 +4452,47 @@ declare namespace webdriver { } /** - * Handles the execution of {@code webdriver.Command} objects. + * Handles the execution of WebDriver {@link Command commands}. + * @interface */ - interface CommandExecutor { - /** - * 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 - * {@link bot.response.ResponseObject} object. - * @param {!webdriver.Command} command The command to execute. - * @param {function(Error, !bot.response.ResponseObject=)} callback the function - * to invoke when the command response is ready. - */ - execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; + 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); } /** @@ -3283,39 +4522,42 @@ declare namespace webdriver { /** * 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 {!Array.<{fn: !Function, oneshot: boolean, - * scope: (Object|undefined)}>} The registered listeners for - * the given event type. + * @return {!Set} The registered listeners for the given event + * type. */ - listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: any;}>; + listeners(type: string): any; /** * Registers a listener. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn 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. + * @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, listenerFn: Function, opt_scope?:any): EventEmitter; + 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} listenerFn The function to invoke when the event is fired. + * @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, listenerFn: any, opt_scope?: any): EventEmitter; + 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} listenerFn The function to invoke when the event is fired. + * @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, listenerFn: Function, opt_scope?:any): EventEmitter; + on(type: string, fn: Function, opt_scope?:any): EventEmitter; /** * Removes a previously registered event listener. @@ -3340,14 +4582,20 @@ declare namespace webdriver { /** * Interface for navigating back and forth in the browser history. */ - interface WebDriverNavigation { + class Navigation { //region Constructors /** - * @param {!webdriver.WebDriver} driver The parent driver. - * @constructor + * 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() */ - new (driver: WebDriver): WebDriverNavigation; + constructor(driver: WebDriver); //endregion @@ -3397,14 +4645,14 @@ declare namespace webdriver { /** * Provides methods for managing browser and driver state. */ - interface WebDriverOptions { + class Options { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: webdriver.WebDriver): WebDriverOptions; + constructor(driver: webdriver.WebDriver); //endregion @@ -3417,13 +4665,13 @@ declare namespace webdriver { * @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 {!webdriver.promise.Promise} A promise that will be resolved when the - * cookie has been added to the page. + * @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): webdriver.promise.Promise; - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; + 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. @@ -3467,19 +4715,19 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Logs} The interface for managing driver * logs. */ - logs(): WebDriverLogs; + logs(): webdriver.Logs; /** * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver * timeouts. */ - timeouts(): WebDriverTimeouts; + timeouts(): webdriver.Timeouts; /** * @return {!webdriver.WebDriver.Window} The interface for managing the * current window. */ - window(): WebDriverWindow; + window(): webdriver.Window; //endregion } @@ -3487,14 +4735,14 @@ declare namespace webdriver { /** * An interface for managing timeout behavior for WebDriver instances. */ - interface WebDriverTimeouts { + class Timeouts { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverTimeouts; + constructor(driver: webdriver.WebDriver); //endregion @@ -3549,7 +4797,7 @@ declare namespace webdriver { /** * An interface for managing the current window. */ - interface WebDriverWindow { + class Window { //region Constructors @@ -3557,7 +4805,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverWindow; + constructor(driver: webdriver.WebDriver); //endregion @@ -3612,7 +4860,7 @@ declare namespace webdriver { /** * Interface for managing WebDriver log records. */ - interface WebDriverLogs { + class Logs { //region Constructors @@ -3620,7 +4868,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverLogs; + constructor(driver: webdriver.WebDriver); //endregion @@ -3640,7 +4888,7 @@ declare namespace webdriver { * promise that will resolve to a list of log entries for the specified * type. */ - get(type: string): webdriver.promise.Promise; + get(type: webdriver.logging.Type): webdriver.promise.Promise; /** * Retrieves the log types available to this driver. @@ -3655,7 +4903,7 @@ declare namespace webdriver { /** * An interface for changing the focus of the driver to another frame or window. */ - interface WebDriverTargetLocator { + class TargetLocator { //region Constructors @@ -3663,7 +4911,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverTargetLocator; + constructor(driver: webdriver.WebDriver); //endregion @@ -3687,44 +4935,47 @@ declare namespace webdriver { /** * Schedules a command to switch the focus of all future commands to another - * frame on the page. - *

    - * If the frame is specified by a number, the command will switch to the frame - * by its (zero-based) index into the {@code window.frames} collection. - *

    - * If the frame is specified by a string, the command will select the frame by - * its name or ID. To select sub-frames, simply separate the frame names/IDs by - * dots. As an example, "main.child" will select the frame with the name "main" - * and then its child "child". - *

    - * If the specified frame can not be found, the deferred result will errback - * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. - * @param {string|number} nameOrIndex The frame locator. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the specified frame. + * 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: string): webdriver.promise.Promise; - frame(nameOrIndex: number): webdriver.promise.Promise; + 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 {@code webdriver.WebDriver#getWindowHandles}). - *

    - * If the specificed window can not be found, the deferred result will errback - * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. + * 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 {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the specified window. + * @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 alert dialog. This command - * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal - * dialog is not currently open. - * @return {!webdriver.Alert} The open alert. + * 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; @@ -3789,27 +5040,14 @@ declare namespace webdriver { //region Constructors /** - * @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a + * @param {!(Session|promise.Promise)} session Either a * known session or a promise that will be resolved to a session. - * @param {!webdriver.CommandExecutor} executor The executor to use when - * sending commands to the browser. - * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * @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 */ - constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - - //endregion - - //region Static Properties - - static Navigation: WebDriverNavigation; - static Options: WebDriverOptions; - static Timeouts: WebDriverTimeouts; - static Window: WebDriverWindow; - static Logs: WebDriverLogs; - static TargetLocator: WebDriverTargetLocator; + constructor(session: Session|webdriver.promise.Promise, executor: Executor, opt_flow?: webdriver.promise.ControlFlow); //endregion @@ -3817,29 +5055,29 @@ declare namespace webdriver { /** * Creates a new WebDriver client for an existing session. - * @param {!webdriver.CommandExecutor} executor Command executor to use when - * querying for session details. + * @param {!command.Executor} executor Command executor to use when querying + * for session details. * @param {string} sessionId ID of the session to attach to. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver - * commands should execute under. Defaults to the - * {@link webdriver.promise.controlFlow() currently active} control flow. - * @return {!webdriver.WebDriver} A new client for the specified session. + * @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: CommandExecutor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static attachToSession(executor: Executor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; /** * Creates a new WebDriver session. - * @param {!webdriver.CommandExecutor} executor The executor to create the new - * session with. - * @param {!webdriver.Capabilities} desiredCapabilities The desired + * @param {!command.Executor} executor The executor to create the new session + * with. + * @param {!./capabilities.Capabilities} desiredCapabilities The desired * capabilities for the new session. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * @param {promise.ControlFlow=} opt_flow The control flow all driver * commands should execute under, including the initial session creation. - * Defaults to the {@link webdriver.promise.controlFlow() currently active} + * Defaults to the {@link promise.controlFlow() currently active} * control flow. - * @return {!webdriver.WebDriver} The driver for the newly created session. + * @return {!WebDriver} The driver for the newly created session. */ - static createSession(executor: CommandExecutor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; //endregion @@ -3852,20 +5090,22 @@ declare namespace webdriver { controlFlow(): webdriver.promise.ControlFlow; /** - * Schedules a {@code webdriver.Command} to be executed by this driver's - * {@code webdriver.CommandExecutor}. - * @param {!webdriver.Command} command The command to schedule. + * 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 {!webdriver.promise.Promise} A promise that will be resolved with - * the command result. + * @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 webdriver.FileDetector file detector} that should be + * Sets the {@linkplain input.FileDetector file detector} that should be * used with this instance. - * @param {webdriver.FileDetector} detector The detector to use or {@code null}. + * @param {input.FileDetector} detector The detector to use or {@code null}. */ setFileDetector(detector: FileDetector): void; @@ -3895,23 +5135,23 @@ declare namespace webdriver { /** * Creates a new action sequence using this driver. The sequence will not be - * scheduled for execution until {@link webdriver.ActionSequence#perform} is + * scheduled for execution until {@link actions.ActionSequence#perform} is * called. Example: - *

    
    -         *   driver.actions().
    -         *       mouseDown(element1).
    -         *       mouseMove(element2).
    -         *       mouseUp().
    -         *       perform();
    -         * 
    - * @return {!webdriver.ActionSequence} A new action sequence for this instance. + * + * 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 webdriver.TouchSequence#perform} is + * scheduled for execution until {@link actions.TouchSequence#perform} is * called. Example: * * driver.touchActions(). @@ -3919,7 +5159,7 @@ declare namespace webdriver { * doubleTap(element2). * perform(); * - * @return {!webdriver.TouchSequence} A new touch sequence for this instance. + * @return {!actions.TouchSequence} A new touch sequence for this instance. */ touchActions(): TouchSequence; @@ -3961,8 +5201,7 @@ declare namespace webdriver { * scripts return value. * @template T */ - executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; - executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute asynchronous JavaScript in the context of the @@ -4179,38 +5418,27 @@ declare namespace webdriver { * 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 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: + * 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 webdriver.promise.filter(links, function(link) { - * return links.isDisplayed(); - * }).then(function(visibleLinks) { - * return visibleLinks[0]; + * return promise.filter(links, function(link) { + * return link.isDisplayed(); * }); * } * - * When running in the browser, a WebDriver cannot manipulate DOM elements - * directly; it may do so only through a {@link webdriver.WebElement} reference. - * This function may be used to generate a WebElement from a DOM element. A - * reference to the DOM element will be stored in a known location and this - * driver will attempt to retrieve it through {@link #executeScript}. If the - * element cannot be found (eg, it belongs to a different document than the - * one this instance is currently focused on), a - * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The - * locator to use. - * @return {!webdriver.WebElement} A WebElement that can be used to issue + * @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(locatorOrElement: Locator|By.Hash|WebElement|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if an element is present on the page. @@ -4219,35 +5447,36 @@ declare namespace webdriver { * 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 {!(webdriver.Locator|webdriver.By.Hash|Element| - * Function)} locatorOrElement The locator to use, or the actual - * DOM element to be located by the server. - * @return {!webdriver.promise.Promise.} A promise that will resolve + * @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: Locator|By.Hash|WebElement|Function): webdriver.promise.Promise; + isElementPresent(locatorOrElement: By|Function): webdriver.promise.Promise; /** * Schedule a command to search for multiple elements on the page. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * strategy to use when searching for the element. - * @return {!webdriver.promise.Promise.>} A + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + 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 screenshot of the entire display containing the browser - *
    * - * @return {!webdriver.promise.Promise.} A promise that will be + * 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; @@ -4256,45 +5485,25 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Options} The options interface for this * instance. */ - manage(): WebDriverOptions; + manage(): webdriver.Options; /** * @return {!webdriver.WebDriver.Navigation} The navigation interface for this * instance. */ - navigate(): WebDriverNavigation; + navigate(): Navigation; /** * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for * this instance. */ - switchTo(): WebDriverTargetLocator; + switchTo(): webdriver.TargetLocator; //endregion } interface IWebElementId { - ELEMENT: string; - } - - /** - * 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; + [ELEMENT:string]: string; } /** @@ -4554,7 +5763,7 @@ declare namespace webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator|By.Hash|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this @@ -4565,7 +5774,7 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. */ - isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + isElementPresent(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that @@ -4576,10 +5785,9 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; } - /** * Defines an object that can be asynchronously serialized to its WebDriver * wire representation. @@ -4600,7 +5808,6 @@ declare namespace webdriver { 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 @@ -4626,35 +5833,59 @@ declare namespace webdriver { */ class WebElement implements Serializable { /** - * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this - * element. - * @param {!(webdriver.promise.Promise.| - * webdriver.WebElement.Id)} id The server-assigned opaque ID for the - * underlying DOM element. - * @constructor + * @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, id: webdriver.promise.Promise|IWebElementId); + constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise|string); /** - * Wire protocol definition of a WebElement ID. - * @typedef {{ELEMENT: string}} - * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * @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 Id: IWebElementId; + static buildId(id: string, opt_noLegacy?: boolean): Object; /** - * The property key used in the wire protocol to indicate that a JSON object - * contains the ID of a WebElement. - * @type {string} - * @const + * 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 ELEMENT_KEY: string; + 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; + 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 @@ -4688,35 +5919,40 @@ declare namespace webdriver { * }); * } * - * @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 + * @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: Locator|By.Hash|Function): WebElementPromise; + 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 + * @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: Locator|By.Hash|Function): webdriver.promise.Promise; + 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 + * @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: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to click on this element. @@ -4727,7 +5963,7 @@ declare namespace webdriver { /** * Schedules a command to type a sequence on the DOM element represented by this - * instance. + * 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 @@ -4799,7 +6035,7 @@ declare namespace webdriver { * * @param {string} cssStyleProperty The name of the CSS style property to look * up. - * @return {!webdriver.promise.Promise.} A promise that will be + * @return {!promise.Promise} A promise that will be * resolved with the requested CSS value. */ getCssValue(cssStyleProperty: string): webdriver.promise.Promise; @@ -4885,10 +6121,10 @@ declare namespace webdriver { 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 + * 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 {!webdriver.promise.Promise.} A promise that will be resolved + * @return {!promise.Promise} A promise that will be resolved * when the element has been cleared. */ clear(): webdriver.promise.Promise; @@ -4900,6 +6136,18 @@ declare namespace webdriver { */ 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 @@ -4907,25 +6155,6 @@ declare namespace webdriver { */ 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; - - /** - * Returns the raw ID string ID for this element. - * @return {!webdriver.promise.Promise} A promise that resolves to this - * element's raw ID as a string value. - * @package - */ - getRawId(): webdriver.promise.Promise; - - /** @override */ - serialize(): 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 @@ -4933,14 +6162,8 @@ declare namespace webdriver { */ getInnerHtml(): webdriver.promise.Promise; - /** - * Compares to WebElements for equality. - * @param {!webdriver.WebElement} a A WebElement. - * @param {!webdriver.WebElement} b A WebElement. - * @return {!webdriver.promise.Promise} A promise that will be resolved to - * whether the two WebElements are equal. - */ - static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; + /** @override */ + serialize(): webdriver.promise.Promise; } /** @@ -4966,6 +6189,14 @@ declare namespace webdriver { * @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. @@ -5075,191 +6306,31 @@ declare namespace webdriver { * @template R */ thenFinally(callback: () => any): webdriver.promise.Promise; - } - namespace By { /** - * Locates elements that have a specific class name. The returned locator - * is equivalent to searching for elements with the CSS selector ".clazz". + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: * - * @param {string} className The class name to search for. - * @return {!webdriver.Locator} 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 - */ - function className(value: string): Locator; - - /** - * Locates elements using a CSS selector. For browsers that do not support - * CSS selectors, WebDriver implementations may return an - * {@linkplain bot.Error.State.INVALID_SELECTOR invalid selector} error. An - * implementation may, however, emulate the CSS selector API. + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {string} selector The CSS selector to use. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/CSS2/selector.html - */ - function css(value: string): Locator; - - /** - * Locates an element by its ID. + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); * - * @param {string} id The ID to search for. - * @return {!webdriver.Locator} The new locator. + * @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 */ - function id(value: string): Locator; - - /** - * Locates link elements whose {@linkplain webdriver.WebElement#getText visible - * text} matches the given string. - * - * @param {string} text The link text to search for. - * @return {!webdriver.Locator} The new locator. - */ - function linkText(value: string): Locator; - - /** - * 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): !webdriver.promise.Promise} A new, - * JavaScript-based locator function. - */ - function js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; - - /** - * Locates elements whose {@code name} attribute has the given value. - * - * @param {string} name The name attribute to search for. - * @return {!webdriver.Locator} The new locator. - */ - function name(value: string): Locator; - - /** - * 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 {!webdriver.Locator} The new locator. - */ - function partialLinkText(value: string): Locator; - - /** - * Locates elements with a given tag name. The returned locator is - * equivalent to using the - * [getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) - * DOM function. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html - */ - function tagName(value: string): Locator; - - /** - * 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 {@code "//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 {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/xpath/ - */ - function xpath(value: string): Locator; - - /** - * 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 Hash = {className: string}| - {css: string}| - {id: string}| - {js: string}| - {linkText: string}| - {name: string}| - {partialLinkText: string}| - {tagName: string}| - {xpath: string}; - } - - /** - * An element locator. - */ - class Locator { - /** - * An element locator. - * @param {string} using The type of strategy to use for this locator. - * @param {string} value The search target of this locator. - * @constructor - */ - constructor(using: string, value: string); - - - /** - * Maps {@link webdriver.By.Hash} keys to the appropriate factory function. - * @type {!Object.} - * @const - */ - static Strategy: { - className: typeof webdriver.By.className; - css: typeof webdriver.By.css; - id: typeof webdriver.By.id; - js: typeof webdriver.By.js; - linkText: typeof webdriver.By.linkText; - name: typeof webdriver.By.name; - partialLinkText: typeof webdriver.By.partialLinkText; - tagName: typeof webdriver.By.tagName; - xpath: typeof webdriver.By.xpath; - }; - - /** - * Verifies that a {@code value} is a valid locator to use for searching for - * elements on the page. - * - * @param {*} value The value to check is a valid locator. - * @return {!(webdriver.Locator|Function)} A valid locator object or function. - * @throws {TypeError} If the given value is an invalid locator. - */ - static checkLocator(value: any): Locator | Function; - - /** - * The search strategy to use when searching for an element. - * @type {string} - */ - using: string; - - /** - * The search target for this locator. - * @type {string} - */ - value: string; - - /** @return {string} String representation of this locator. */ - toString(): string; + catch(errback: Function): webdriver.promise.Promise; } /** @@ -5275,8 +6346,7 @@ declare namespace webdriver { * capabilities. * @constructor */ - constructor(id: string, capabilities: Capabilities); - constructor(id: string, capabilities: any); + constructor(id: string, capabilities: Capabilities|Object); //endregion @@ -5290,7 +6360,7 @@ declare namespace webdriver { /** * @return {!webdriver.Capabilities} This session's capabilities. */ - getCapabilities(): Capabilities; + getCapabilities(): webdriver.Capabilities; /** * Retrieves the value of a specific capability. @@ -5376,10 +6446,6 @@ declare module 'selenium-webdriver/chrome' { export = chrome; } -declare module 'selenium-webdriver/firefox' { - export = firefox; -} - declare module 'selenium-webdriver/executors' { export = executors; } From ab5876b6df73ae917772efcc161efe635d019b51 Mon Sep 17 00:00:00 2001 From: rvassar Date: Wed, 14 Sep 2016 09:17:23 -0700 Subject: [PATCH 495/844] Updated the Attribution class with constructor and methods. --- openlayers/openlayers.d.ts | 62 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/openlayers/openlayers.d.ts b/openlayers/openlayers.d.ts index 7cc216f1c2..346a9edef6 100644 --- a/openlayers/openlayers.d.ts +++ b/openlayers/openlayers.d.ts @@ -88,6 +88,34 @@ declare namespace olx { target?: Element; } + interface AttributionControlOptions { + /*** CSS class name. Default is ol-attribution.*/ + className?: string; + /*** Target.*/ + target?: Element; + /** + * Specify if attributions can be collapsed. If you use an OSM source, + * should be set to false — see OSM Copyright — Default is true. + */ + collapsible?: boolean; + /*** Specify if attributions should be collapsed at startup. Default is true.*/ + collapsed?: boolean; + /*** Text label to use for the button tip. Default is "Attributions".*/ + tipLabel?: Array | ol.Collection; + /** + * Text label to use for the collapsed attributions button. Default is i. + * Instead of text, also a Node (e.g. a span element) can be used. + */ + label?: string | Node; + /** + * Text label to use for the expanded attributions button. Default is ». + * Instead of text, also a Node (e.g. a span element) can be used. + */ + collapseLabel?: string | Node; + /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ + render?: Function; + } + interface AttributionOptions { /** HTML markup for this attribution. */ @@ -2841,7 +2869,41 @@ declare namespace ol { } + /** + * Control to show all the attributions associated with the layer sources in the map. + * This control is one of the default controls included in maps. By default it will show in the bottom right portion of the map, + * but this can be changed by using a css selector for .ol-attribution. + */ class Attribution extends Control { + constructor(opt_options?: olx.AttributionControlOptions); + /** + * Update the attribution element. + * @param mapEvent + */ + render(mapEvent: ol.MapEvent): void; + + /** + * Return true when the attribution is currently collapsed or false otherwise. + */ + getCollapsed(): boolean; + + /** + * Return true if the attribution is collapsible, false otherwise. + */ + getCollapsible(): boolean; + + /** + * Collapse or expand the attribution according to the passed parameter. Will not do anything if the attribution isn't + * collapsible or if the current collapsed state is already the one requested. + * @param collapsed + */ + setCollapsed(collapsed: boolean): void; + + /** + * Set whether the attribution should be collapsible. + * @param collapsible + */ + setCollapsible(collapsible: boolean): void; } class FullScreen extends Control { From 47588ba8f9a2ceb05acef2ec2c69263cf057405d Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Wed, 14 Sep 2016 11:27:33 -0700 Subject: [PATCH 496/844] [knockout] Introduce specialized signatures for subscribe method, specifically common "change" and "beforeChange" Add subscribe for "arrayChange" event for observable array (fixes #11203) Improve KnockoutArrayChange status typing. --- knockout/knockout.d.ts | 11 ++++++++-- knockout/knockoutamd-tests.ts | 2 +- knockout/tests/knockout-tests.ts | 35 ++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 3 deletions(-) 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 From 27347de728273acb8e0dcc917753164c96acb6a0 Mon Sep 17 00:00:00 2001 From: Nick Graef Date: Wed, 14 Sep 2016 14:13:28 -0500 Subject: [PATCH 497/844] add route-bound methods for scoped service Documentation: https://github.com/mgonto/restangular#decoupled-restangular-service When configured via `Restangular.service('route')`, the route is bound to some functions. This change overrides those functions with the correct signatures. --- restangular/restangular.d.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/restangular/restangular.d.ts b/restangular/restangular.d.ts index 8daa5c0b08..dd059cea2e 100644 --- a/restangular/restangular.d.ts +++ b/restangular/restangular.d.ts @@ -90,11 +90,20 @@ declare namespace restangular { withConfig(configurer: (RestangularProvider: IProvider) => any): IService; restangularizeElement(parent: any, element: any, route: string, collection?: any, reqParams?: any): IElement; restangularizeCollection(parent: any, element: any, route: string): ICollection; - service(route: string, parent?: any): IService; + service(route: string, parent?: any): IScopedService; stripRestangular(element: any): any; extendModel(route: string, extender: (model: IElement) => any): void; extendCollection(route: string, extender: (collection: ICollection) => any): void; } + + interface IScopedService extends IService { + one(id: number): IElement; + one(id: string): IElement; + post(elementToPost: any, queryParams?: any, headers?: any): IPromise; + post(elementToPost: T, queryParams?: any, headers?: any): IPromise; + getList(queryParams?: any, headers?: any): ICollectionPromise; + getList(queryParams?: any, headers?: any): ICollectionPromise; + } interface IElement extends IService { get(queryParams?: any, headers?: any): IPromise; From 36d40a63a05b5cb3413737fbdf7c9a2a26f211fd Mon Sep 17 00:00:00 2001 From: Craig Date: Wed, 14 Sep 2016 16:56:35 -0700 Subject: [PATCH 498/844] types(selenium-webdriver): revert 2.44 as default (#11226) - previous change would break installing angular-protractor ambient types - adding myself as author --- angular-protractor/angular-protractor.d.ts | 2 +- protractor-helpers/protractor-helpers.d.ts | 2 +- .../protractor-http-mock.d.ts | 2 +- .../selenium-webdriver-2.53.1-tests.ts | 1144 +++++ ....0.d.ts => selenium-webdriver-2.53.1.d.ts} | 3994 ++++++++++------ .../selenium-webdriver-tests.ts | 249 +- selenium-webdriver/selenium-webdriver.d.ts | 4250 ++++++----------- 7 files changed, 5444 insertions(+), 4199 deletions(-) create mode 100644 selenium-webdriver/selenium-webdriver-2.53.1-tests.ts rename selenium-webdriver/{selenium-webdriver-2.44.0.d.ts => selenium-webdriver-2.53.1.d.ts} (60%) diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index add8264b7e..d33eeddace 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -3,7 +3,7 @@ // Definitions by: Bill Armstrong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace protractor { //region Wrapped webdriver Items diff --git a/protractor-helpers/protractor-helpers.d.ts b/protractor-helpers/protractor-helpers.d.ts index 16d67cfbb9..3966acd36e 100644 --- a/protractor-helpers/protractor-helpers.d.ts +++ b/protractor-helpers/protractor-helpers.d.ts @@ -5,7 +5,7 @@ /// /// -/// +/// // ElementArrayFinder diff --git a/protractor-http-mock/protractor-http-mock.d.ts b/protractor-http-mock/protractor-http-mock.d.ts index 2300246e43..29d6dfb276 100644 --- a/protractor-http-mock/protractor-http-mock.d.ts +++ b/protractor-http-mock/protractor-http-mock.d.ts @@ -3,7 +3,7 @@ // Definitions by: Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace mock { interface ProtractorHttpMock { 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.44.0.d.ts b/selenium-webdriver/selenium-webdriver-2.53.1.d.ts similarity index 60% rename from selenium-webdriver/selenium-webdriver-2.44.0.d.ts rename to selenium-webdriver/selenium-webdriver-2.53.1.d.ts index 548048b695..a6e419755d 100644 --- a/selenium-webdriver/selenium-webdriver-2.44.0.d.ts +++ b/selenium-webdriver/selenium-webdriver-2.53.1.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 +// 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 { @@ -19,8 +19,7 @@ declare namespace chrome { * {@code null} to use the currently active flow. * @constructor */ - constructor(opt_config?: webdriver.Capabilities, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); - constructor(opt_config?: Options, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: Options|webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); } interface IOptionsValues { @@ -240,6 +239,53 @@ declare namespace chrome { 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. @@ -255,21 +301,6 @@ declare namespace chrome { * @return {!webdriver.Capabilities} The capabilities. */ toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; - - - /** - * Converts this instance to its JSON wire protocol representation. Note this - * function is an implementation not intended for general use. - * @return {{args: !Array., - * binary: (string|undefined), - * detach: boolean, - * extensions: !Array., - * localState: (Object|undefined), - * logFile: (string|undefined), - * prefs: (Object|undefined)}} The JSON wire protocol representation - * of this instance. - */ - toJSON(): IOptionsValues; } /** @@ -348,8 +379,7 @@ declare namespace chrome { * configuration to use. * @return {!ServiceBuilder} A self reference. */ - setStdio(config: string): ServiceBuilder; - setStdio(config: any[]): ServiceBuilder; + setStdio(config: string|Array): ServiceBuilder; /** @@ -368,7 +398,7 @@ declare namespace chrome { * @throws {Error} If the driver exectuable was not specified and a default * could not be found on the current PATH. */ - build(): any; + build(): remote.DriverService; } /** @@ -377,395 +407,1325 @@ declare namespace chrome { * a ChromeDriver executable found on the system PATH. * @return {!remote.DriverService} The default ChromeDriver service. */ - function getDefaultService(): any; + 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: any): void; + function setDefaultService(service: remote.DriverService): void; } -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); +declare namespace edge { - /** - * 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; - } - - /** - * A WebDriver client for Firefox. - * - * @extends {webdriver.WebDriver} - */ class Driver extends webdriver.WebDriver { - /** - * @param {(Options|webdriver.Capabilities|Object)=} opt_config The - * configuration options for this driver, specified as either an - * {@link Options} or {@link webdriver.Capabilities}, or as a raw hash - * object. - * @param {webdriver.promise.ControlFlow=} opt_flow The flow to - * schedule commands through. Defaults to the active flow object. - * @constructor - */ - constructor(opt_config?: webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); - constructor(opt_config?: any, opt_flow?: webdriver.promise.ControlFlow); + /** + * @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; } /** - * Configuration options for the FirefoxDriver. + * Class for managing MicrosoftEdgeDriver specific options. */ class Options { - /** - * @constructor - */ - constructor(); - /** - * 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): Options; - setProfile(profile: Profile): 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 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): Options; - setBinary(binary: Binary): 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; - - /** - * Sets the logging preferences for the new session. - * @param {webdriver.logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; - - - /** - * Sets the proxy to use. - * - * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - - /** - * Converts these options to a {@link webdriver.Capabilities} instance. - * - * @return {!webdriver.Capabilities} A new capabilities object. - */ - toCapabilities(opt_remote?: any): webdriver.Capabilities; + /** + * 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; } /** - * Models a Firefox proifle directory for use with the FirefoxDriver. The - * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} - * is called. + * Creates {@link remote.DriverService} instances that manage a + * MicrosoftEdgeDriver server in a child process. */ - 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); + 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); - /** - * 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; + /** + * 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; - /** - * 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; + /** + * 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; - - /** - * 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; + /** + * 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 url The server's URL, or a promise that will resolve to that URL. - * @returns {!webdriver.CommandExecutor} The new command executor. + * @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.CommandExecutor; - function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; + 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 { - interface IErrorCode { - SUCCESS: number; + class IError extends Error { + constructor(opt_error?: string); - NO_SUCH_ELEMENT: number; - NO_SUCH_FRAME: number; - UNKNOWN_COMMAND: number; - UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. - STALE_ELEMENT_REFERENCE: number; - ELEMENT_NOT_VISIBLE: number; - INVALID_ELEMENT_STATE: number; - UNKNOWN_ERROR: number; - ELEMENT_NOT_SELECTABLE: number; - JAVASCRIPT_ERROR: number; - XPATH_LOOKUP_ERROR: number; - TIMEOUT: number; - NO_SUCH_WINDOW: number; - INVALID_COOKIE_DOMAIN: number; - UNABLE_TO_SET_COOKIE: number; - MODAL_DIALOG_OPENED: number; - UNEXPECTED_ALERT_OPEN: number; - NO_SUCH_ALERT: number; - NO_MODAL_DIALOG_OPEN: number; - SCRIPT_TIMEOUT: number; - INVALID_ELEMENT_COORDINATES: number; - IME_NOT_AVAILABLE: number; - IME_ENGINE_ACTIVATION_FAILED: number; - INVALID_SELECTOR_ERROR: number; - SESSION_NOT_CREATED: number; - MOVE_TARGET_OUT_OF_BOUNDS: number; - SQL_DATABASE_ERROR: number; - INVALID_XPATH_SELECTOR: number; - INVALID_XPATH_SELECTOR_RETURN_TYPE: number; - // The following error codes are derived straight from HTTP return codes. - METHOD_NOT_ALLOWED: number; + code(): number; } - var ErrorCode: IErrorCode; + /** + * 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); + } /** - * Error extension that includes error status codes from the WebDriver wire - * protocol: - * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes - * - * @extends {Error} + * An attempt was made to select an element that cannot be selected. */ - class Error { + class ElementNotSelectableError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Constructors + /** + * 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); + } - /** - * @param {!bot.ErrorCode} code The error's status code. - * @param {string=} opt_message Optional error message. - * @constructor - */ - constructor(code: number, opt_message?: 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); + } - //endregion + /** + * 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); + } - //region Static Properties + /** + * 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); + } - /** - * Status strings enumerated in the W3C WebDriver working draft. - * @enum {string} - * @see http://www.w3.org/TR/webdriver/#status-codes - */ - static State: { - ELEMENT_NOT_SELECTABLE: string; - ELEMENT_NOT_VISIBLE: string; - IME_ENGINE_ACTIVATION_FAILED: string; - IME_NOT_AVAILABLE: string; - INVALID_COOKIE_DOMAIN: string; - INVALID_ELEMENT_COORDINATES: string; - INVALID_ELEMENT_STATE: string; - INVALID_SELECTOR: string; - JAVASCRIPT_ERROR: string; - MOVE_TARGET_OUT_OF_BOUNDS: string; - NO_SUCH_ALERT: string; - NO_SUCH_DOM: string; - NO_SUCH_ELEMENT: string; - NO_SUCH_FRAME: string; - NO_SUCH_WINDOW: string; - SCRIPT_TIMEOUT: string; - SESSION_NOT_CREATED: string; - STALE_ELEMENT_REFERENCE: string; - SUCCESS: string; - TIMEOUT: string; - UNABLE_TO_SET_COOKIE: string; - UNEXPECTED_ALERT_OPEN: string; - UNKNOWN_COMMAND: string; - UNKNOWN_ERROR: string; - UNSUPPORTED_OPERATION: 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); + } - //endregion + /** + * Argument was an invalid selector. + */ + class InvalidSelectorError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Properties + /** + * 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); + } - /** - * This error's status code. - * @type {!bot.ErrorCode} - */ - code: number; + /** + * 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); + } - /** @type {string} */ - state: 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); + } - /** @override */ - message: 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); + } - /** @override */ - name: 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); + } - /** @override */ - stack: 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); + } - /** - * Flag used for duck-typing when this code is embedded in a Firefox extension. - * This is required since an Error thrown in one component and then reported - * to another will fail instanceof checks in the second component. - * @type {boolean} - */ - isAutomationError: boolean; + /** + * 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); + } - //endregion + /** + * 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); + } - //region Methods + /** + * A new session could not be created. + */ + class SessionNotCreatedError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @return {string} The string representation of this error. */ - toString(): 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); + } - //endregion + /** + * 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); } } @@ -776,48 +1736,96 @@ declare namespace webdriver { * @typedef {Object.} */ class Preferences { - setLevel(type: string, level: ILevel): void; + setLevel(type: string|Type, level: Level|string|number): void; toJSON(): { [key: string]: string }; } - interface IType { - /** Logs originating from the browser. */ - BROWSER: string; - /** Logs from a WebDriver client. */ - CLIENT: string; - /** Logs from a WebDriver implementation. */ - DRIVER: string; - /** Logs related to performance. */ - PERFORMANCE: string; - /** Logs from the remote server. */ - SERVER: string; - } - /** * Common log types. * @enum {string} */ - var Type: IType; + 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 + } /** - * Logging levels. - * @enum {{value: number, name: webdriver.logging.LevelName}} + * Defines a message level that may be used to control logging output. + * + * @final */ - interface ILevel { - value: number; - name: string; - } + 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); - interface ILevelValues { - ALL: ILevel; - DEBUG: ILevel; - INFO: ILevel; - WARNING: ILevel; - SEVERE: ILevel; - OFF: ILevel; - } + /** @override */ + toString(): string; - var Level: ILevelValues; + /** 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. @@ -827,75 +1835,209 @@ declare namespace webdriver { * convert . * @return {!webdriver.logging.Level} The converted level. */ - function getLevel(nameOrValue: string): ILevel; - function getLevel(nameOrValue: number): ILevel; + function getLevel(nameOrValue: string|number): Level; interface IEntryJSON { - level: string; - message: string; - timestamp: number; - type: string; + 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); - //region Constructors + /** @type {!webdriver.logging.Level} */ + level: Level; - /** - * @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: ILevel, message: string, opt_timestamp?:number, opt_type?:string); - constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); + /** @type {string} */ + message: string; - //endregion + /** @type {number} */ + timestamp: number; - //region Public Properties + /** @type {string} */ + type: string; - /** @type {!webdriver.logging.Level} */ - level: ILevel; + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + } - /** @type {string} */ - message: string; + /** + * 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); - /** @type {number} */ - timestamp: number; + /** @private {string} */ + name_: string; + /** @private {Level} */ + level_: Level; + /** @private {Logger} */ + parent_: Logger; + /** @private {Set} */ + handlers_: any; - /** @type {string} */ - type: string; + /** @return {string} the name of this logger. */ + getName(): string; - //endregion + /** + * @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; - //region Static Methods + /** @return {Level} the log level for this logger. */ + getLevel(): Level; - /** - * Converts a {@link goog.debug.LogRecord} into a - * {@link webdriver.logging.Entry}. - * @param {!goog.debug.LogRecord} logRecord The record to convert. - * @param {string=} opt_type The log type. - * @return {!webdriver.logging.Entry} The converted entry. - */ - static fromClosureLogRecord(logRecord: any, opt_type?:string): Entry; + /** + * @return {!Level} the effective level for this logger. + */ + getEffectiveLevel(): Level; - //endregion + /** + * @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; - //region Methods + /** + * 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; - /** - * @return {{level: string, message: string, timestamp: number, - * type: string}} The JSON representation of this entry. - */ - toJSON(): IEntryJSON; + /** + * 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; - //endregion + /** + * 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; } } @@ -908,15 +2050,15 @@ declare namespace webdriver { * input array's promises are rejected, the returned promise will be rejected * with the same reason. * - * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of + * @param {!Array<(T|!ManagedPromise)>} arr An array of * promises to wait on. - * @return {!webdriver.promise.Promise.>} A promise that is + * @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: Promise[]): Promise; + function all(arr: Array>): Promise; /** * Invokes the appropriate callback function as soon as a promised @@ -939,9 +2081,9 @@ declare namespace webdriver { * 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(!webdriver.promise.ControlFlow)} callback The entry point + * @param {function(!ControlFlow)} callback The entry point * to the newly created flow. - * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * @return {!ManagedPromise} A promise that resolves to the callback * result. */ function createFlow(callback: (flow: ControlFlow) => R): Promise; @@ -966,7 +2108,7 @@ declare namespace webdriver { * 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 {!webdriver.promise.Promise} The promise. + * @return {!ManagedPromise} The promise. */ function delayed(ms: number): Promise; @@ -974,26 +2116,25 @@ declare namespace webdriver { * 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 + * 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 + * 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.|webdriver.promise.Promise.>)} arr The + * @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|webdriver.promise.Promise.)} fn The function + * @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: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise; - function filter(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function filter(arr: Array|Promise>, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; /** * Creates a new deferred object. @@ -1003,8 +2144,9 @@ declare namespace webdriver { /** * Creates a promise that has been resolved with the given value. - * @param {*=} opt_value The resolved value. - * @return {!webdriver.promise.Promise} The resolved promise. + * @param {T=} opt_value The resolved value. + * @return {!ManagedPromise} The resolved promise. + * @template T */ function fulfilled(opt_value?: T): Promise; @@ -1013,42 +2155,44 @@ declare namespace webdriver { * 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 + * 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 + * 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.|webdriver.promise.Promise.>)} arr The + * @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 + * @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: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise - function map(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + 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 {!webdriver.promise.Promise} The rejected promise. + * @return {!ManagedPromise} The rejected promise. + * @template T */ - function rejected(opt_reason?: any): Promise; + function rejected(opt_reason?: any): Promise; /** - * Wraps a function that is assumed to be a node-style callback as its final - * argument. This callback takes two arguments: an error value (which will be + * 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. - * If the call fails, the returned promise will be rejected, otherwise it will - * be resolved with the result. + * The callback will the resolve or reject the returned promise, based on its + * arguments. * @param {!Function} fn The function to wrap. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * @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; @@ -1059,37 +2203,35 @@ declare namespace webdriver { * 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. - *

    
    -         * webdriver.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 1:__ the Fibonacci Sequence. * - *

    Example 2: a generator that throws. - *

    
    -         * webdriver.promise.consume(function* () {
    -         *   yield webdriver.promise.delayed(250).then(function() {
    -         *     throw Error('boom');
    -         *   });
    -         * }).thenCatch(function(e) {
    -         *   console.log(e.toString());  // Error: boom
    -         * });
    -         * 
    + * 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 {!webdriver.promise.Promise.} A promise that will resolve to the + * @return {!ManagedPromise} A promise that will resolve to the * generator's final result. * @throws {TypeError} If the given function is not a generator. */ @@ -1104,10 +2246,9 @@ declare namespace webdriver { * resolved successfully. * @param {Function=} opt_errback The function to call when the value is * rejected. - * @return {!webdriver.promise.Promise} A new promise. + * @return {!ManagedPromise} A new promise. */ - function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; - function when(value: Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): 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 @@ -1120,19 +2261,19 @@ declare namespace webdriver { * Warning: This function makes no checks against objects that contain * cyclical references: * - * var value = {}; - * value['self'] = value; - * webdriver.promise.fullyResolved(value); // Stack overflow. + * var value = {}; + * value['self'] = value; + * promise.fullyResolved(value); // Stack overflow. * * @param {*} value The value to fully resolve. - * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * @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 {!webdriver.promise.ControlFlow} flow The new default flow. + * @param {!ControlFlow} flow The new default flow. * @throws {Error} If the default flow is not currently active. */ function setDefaultFlow(flow: ControlFlow): void; @@ -1141,265 +2282,181 @@ declare namespace webdriver { /** * Error used when the computation of a promise is cancelled. - * - * @extends {goog.debug.Error} - * @final */ - class CancellationError { - /** - * @param {string=} opt_msg The cancellation message. - * @constructor - */ - constructor(opt_msg?: string); - - name: string; - message: string; + 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 alreayd been resolved. + * 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=} opt_reason The reason this promise is being cancelled. + * @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): void; - + 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 opt_callback The + * @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 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 + * @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) => Promise, opt_errback?: (error: any) => any): 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: T) => R, opt_errback?: (error: any) => any): Promise; - + 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().thenCatch(function(ex) {
    -             *     console.error(ex);
    -             *   });
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (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 + * // 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 */ - thenCatch(errback: (error: any) => any): 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): Promise; + 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 - */ + * 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 alreayd been resolved. + * 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=} opt_reason The reason this promise is being cancelled. + * @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): void; - + 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 opt_callback The + * @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 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 + * @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) => Promise, opt_errback?: (error: any) => any): 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: T) => R, opt_errback?: (error: any) => any): Promise; - + 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().thenCatch(function(ex) {
    -             *     console.error(ex);
    -             *   });
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (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 + * // 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 */ - thenCatch(errback: (error: any) => any): Promise; - + 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);
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } finally { + * cleanUp(); + * } * - * Note: similar to the {@code finally} clause, if the registered + * // 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
    -             *   }
                  *
    -             *   webdriver.promise.rejected(Error('one'))
    -             *       .thenFinally(function() {
    -             *         throw Error('two');  // Hides Error: one
    -             *       });
    -             * 
    + * 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|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * @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 */ - thenFinally(callback: () => any): Promise; + 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: webdriver.promise.Thenable, ...[?])} ctor The + * 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 webdriver.promise.Thenable.addImplementation}. + * 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. @@ -1432,12 +2489,11 @@ declare namespace webdriver { * 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 {promise.ControlFlow=} opt_flow The control flow + * 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 - */ + */ constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); constructor(); // For angular-protractor/angular-protractor-tests.ts @@ -1450,7 +2506,7 @@ declare namespace webdriver { * {@code Error}, one will be created using the value's string * representation. */ - cancel(reason: any): void; + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; @@ -1468,23 +2524,7 @@ declare namespace webdriver { * @return A new promise which will be resolved * with the result of the invoked callback. */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * 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?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: Function, opt_errback?: Function): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous @@ -1512,6 +2552,31 @@ declare namespace webdriver { */ 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 @@ -1552,7 +2617,7 @@ declare namespace webdriver { * with the callback result. * @template R */ - thenFinally(callback: () => any): Promise; + thenFinally(callback: Function): Promise; //endregion } @@ -1791,107 +2856,6 @@ declare namespace webdriver { } } - namespace stacktrace { - /** - * Class representing one stack frame. - */ - class Frame { - /** - * @param {(string|undefined)} context Context object, empty in case of global - * functions or if the browser doesn't provide this information. - * @param {(string|undefined)} name Function name, empty in case of anonymous - * functions. - * @param {(string|undefined)} alias Alias of the function if available. For - * example the function name will be 'c' and the alias will be 'b' if the - * function is defined as a.b = function c() {};. - * @param {(string|undefined)} path File path or URL including line number and - * optionally column number separated by colons. - * @constructor - */ - constructor(context?: string, name?: string, alias?: string, path?: string); - - /** - * @return {string} The function name or empty string if the function is - * anonymous and the object field which it's assigned to is unknown. - */ - getName(): string; - - - /** - * @return {string} The url or empty string if it is unknown. - */ - getUrl(): string; - - - /** - * @return {number} The line number if known or -1 if it is unknown. - */ - getLine(): number; - - - /** - * @return {number} The column number if known and -1 if it is unknown. - */ - getColumn(): number; - - - /** - * @return {boolean} Whether the stack frame contains an anonymous function. - */ - isAnonymous(): boolean; - - - /** - * Converts this frame to its string representation using V8's stack trace - * format: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi - * @return {string} The string representation of this frame. - * @override - */ - toString(): string; - } - - /** - * Stores a snapshot of the stack trace at the time this instance was created. - * The stack trace will always be adjusted to exclude this function call. - */ - class Snapshot { - /** - * @param {number=} opt_slice The number of frames to remove from the top of - * the generated stack trace. - * @constructor - */ - constructor(opt_slice?: number); - - /** - * @return {!Array.} The parsed stack trace. - */ - getStacktrace(): Frame[]; - } - - /** - * Formats an error's stack trace. - * @param {!(Error|goog.testing.JsUnitException)} error The error to format. - * @return {!(Error|goog.testing.JsUnitException)} The formatted error. - */ - function format(error: any): any; - - /** - * Gets the native stack trace if available otherwise follows the call chain. - * The generated trace will exclude all frames up to and including the call to - * this function. - * @return {!Array.} The frames of the stack trace. - */ - function get(): Frame[]; - - /** - * Whether the current browser supports stack traces. - * - * @type {boolean} - * @const - */ - var BROWSER_SUPPORTED: boolean; - } - namespace until { /** * Defines a condition to @@ -1915,32 +2879,31 @@ declare namespace webdriver { /** * 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 {@code 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. - *
    + * to the designated frame. The target frame may be specified as * - *

    Upon successful resolution of this condition, the driver will be left + * 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| - * webdriver.Locator|webdriver.By.Hash| - * function(!webdriver.WebDriver): !webdriver.WebElement)} frame + * @param {!(number|./webdriver.WebElement|By| + * function(!./webdriver.WebDriver): !./webdriver.WebElement)} frame * The frame identifier. - * @return {!until.Condition.} A new condition. + * @return {!Condition} A new condition. */ - function ableToSwitchToFrame(frame: number|WebElement|Locator|By.Hash|((webdriver: WebDriver)=>WebElement)): 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 {!until.Condition.} The new condition. + * @return {!Condition} The new condition. */ function alertIsPresent(): Condition; @@ -2000,13 +2963,12 @@ declare namespace webdriver { /** * Creates a condition that will loop until an element is - * {@link webdriver.WebDriver#findElement found} with the given locator. + * {@link ./webdriver.WebDriver#findElement found} with the given locator. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. + * @param {!(By|Function)} locator The locator to use. * @return {!until.Condition.} The new condition. */ - function elementLocated(locator: Locator|By.Hash|Function): Condition; + function elementLocated(locator: By|Function): Condition; /** * Creates a condition that will wait for the given element's @@ -2039,7 +3001,7 @@ declare namespace webdriver { * * @param {!webdriver.WebElement} element The element to test. * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. * @see webdriver.WebDriver#getText */ function elementTextMatches(element: WebElement, regex: RegExp): Condition; @@ -2053,7 +3015,7 @@ declare namespace webdriver { * @return {!until.Condition.>} The new * condition. */ - function elementsLocated(locator: Locator|By.Hash|Function): Condition; + function elementsLocated(locator: By|Function): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -2061,7 +3023,7 @@ declare namespace webdriver { * has loaded. * * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. */ function stalenessOf(element: WebElement): Condition; @@ -2080,7 +3042,7 @@ declare namespace webdriver { * given value. * * @param {string} title The expected page title. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. */ function titleIs(title: string): Condition; @@ -2105,18 +3067,18 @@ declare namespace webdriver { } /** - * Enumeration of the buttons used in the advanced interactions API. - * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. - * @enum {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} */ - interface IButton { - LEFT: number; - MIDDLE: number; - RIGHT: number; + enum Button { + LEFT, + MIDDLE, + RIGHT, } - var Button: IButton; - /** * Representations of pressable keys that aren't text. These are stored in * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to @@ -2124,102 +3086,86 @@ declare namespace webdriver { * * @enum {string} */ - interface IKey { - NULL: string; - CANCEL: string; // ^break - HELP: string; - BACK_SPACE: string; - TAB: string; - CLEAR: string; - RETURN: string; - ENTER: string; - SHIFT: string; - CONTROL: string; - ALT: string; - PAUSE: string; - ESCAPE: string; - SPACE: string; - PAGE_UP: string; - PAGE_DOWN: string; - END: string; - HOME: string; - ARROW_LEFT: string; - LEFT: string; - ARROW_UP: string; - UP: string; - ARROW_RIGHT: string; - RIGHT: string; - ARROW_DOWN: string; - DOWN: string; - INSERT: string; - DELETE: string; - SEMICOLON: string; - EQUALS: 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: string; // number pad keys - NUMPAD1: string; - NUMPAD2: string; - NUMPAD3: string; - NUMPAD4: string; - NUMPAD5: string; - NUMPAD6: string; - NUMPAD7: string; - NUMPAD8: string; - NUMPAD9: string; - MULTIPLY: string; - ADD: string; - SEPARATOR: string; - SUBTRACT: string; - DECIMAL: string; - DIVIDE: string; + NUMPAD0, // number pad keys + NUMPAD1, + NUMPAD2, + NUMPAD3, + NUMPAD4, + NUMPAD5, + NUMPAD6, + NUMPAD7, + NUMPAD8, + NUMPAD9, + MULTIPLY, + ADD, + SEPARATOR, + SUBTRACT, + DECIMAL, + DIVIDE, - F1: string; // function keys - F2: string; - F3: string; - F4: string; - F5: string; - F6: string; - F7: string; - F8: string; - F9: string; - F10: string; - F11: string; - F12: string; + F1, // function keys + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, - COMMAND: string; // Apple command key - META: string; // alias for Windows key + COMMAND, // Apple command key + META // alias for Windows key - /** - * Simulate pressing many keys at once in a "chord". Takes a sequence of - * {@link webdriver.Key}s or strings, appends each of the values to a string, - * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns - * the resultant string. - * - * Note: when the low-level webdriver key handlers see Keys.NULL, active - * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. - * - * @param {...string} var_args The key sequence to concatenate. - * @return {string} The null-terminated key sequence. - * @see http://code.google.com/p/webdriver/issues/detail?id=79 - */ - chord: (...var_args: string[]) => string; } - var Key: IKey; - /** * Class for defining sequences of complex user interactions. Each sequence * will not be executed until {@link #perform} is called. * - *

    Example:

    
    -     *   new webdriver.ActionSequence(driver).
    -     *       keyDown(webdriver.Key.SHIFT).
    -     *       click(element1).
    -     *       click(element2).
    -     *       dragAndDrop(element3, element4).
    -     *       keyUp(webdriver.Key.SHIFT).
    -     *       perform();
    -     * 
    + * Example: + * + * new ActionSequence(driver). + * keyDown(Key.SHIFT). + * click(element1). + * click(element2). + * dragAndDrop(element3, element4). + * keyUp(Key.SHIFT). + * perform(); * */ class ActionSequence { @@ -2247,14 +3193,18 @@ declare namespace webdriver { * 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 An optional offset, in pixels. - * Defaults to (0, 0). - * @return {!webdriver.ActionSequence} A self reference. + * + * @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, opt_offset?: ILocation): ActionSequence; - mouseMove(location: ILocation): ActionSequence; + mouseMove(location: WebElement|ILocation, opt_offset?: ILocation): ActionSequence; /** * Presses a mouse button. The mouse button will not be released until @@ -2262,100 +3212,101 @@ declare namespace webdriver { * 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 + * 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 - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).mouseDown() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * 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 webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @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 {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - mouseDown(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - mouseDown(opt_elementOrButton?: number): ActionSequence; + 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 + * 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 - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).mouseUp() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * 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 webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @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 {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - mouseUp(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - mouseUp(opt_elementOrButton?: number): ActionSequence; + 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 {!webdriver.ActionSequence} A self reference. + * + * @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): ActionSequence; - dragAndDrop(element: WebElement, location: ILocation): ActionSequence; + 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 + * 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|webdriver.Button)=} opt_elementOrButton Either + * 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 webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @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 {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - click(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - click(opt_elementOrButton?: number): ActionSequence; + 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 + * 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 - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).doubleClick() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * 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 webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @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 {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - doubleClick(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - doubleClick(opt_elementOrButton?: number): ActionSequence; + doubleClick(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Performs a modifier key press. The modifier key is not released @@ -2366,7 +3317,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyDown(key: string): ActionSequence; + keyDown(key: Key): ActionSequence; /** * Performs a modifier key release. The release is targetted at the currently @@ -2376,7 +3327,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyUp(key: string): ActionSequence; + keyUp(key: Key): ActionSequence; /** * Simulates typing multiple keys. Each modifier key encountered in the @@ -2387,7 +3338,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - sendKeys(...var_args: any[]): ActionSequence; + sendKeys(...var_args: Array): ActionSequence; //endregion } @@ -2483,7 +3434,6 @@ declare namespace webdriver { */ scroll(offset: IOffset): TouchSequence; - /** * Scrolls the touch screen, starting on `elem` and moving by the specified * offset. @@ -2494,7 +3444,6 @@ declare namespace webdriver { */ scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; - /** * Flick, starting anywhere on the screen, at speed xspeed and yspeed. * @@ -2504,7 +3453,6 @@ declare namespace webdriver { */ flick(speed: ISpeed): TouchSequence; - /** * Flick starting at elem and moving by x and y at specified speed. * @@ -2516,26 +3464,29 @@ declare namespace webdriver { 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}). */ - interface Alert { + 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 @@ -2547,6 +3498,18 @@ declare namespace webdriver { */ 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 @@ -2580,47 +3543,27 @@ declare namespace webdriver { * 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();
          *     });
    -     * 
    * - * @param {!webdriver.WebDriver} driver The driver controlling the browser this - * alert is attached to. - * @param {!webdriver.promise.Thenable.} alert A thenable - * that will be fulfilled with the promised alert. - * @constructor - * @extends {webdriver.Alert} - * @implements {webdriver.promise.Thenable.} + * @implements {promise.Thenable.} * @final */ - interface AlertPromise extends Alert, webdriver.promise.IThenable { + 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); } - /** - * An error returned to indicate that there is an unhandled modal dialog on the - * current page. - * @extends {bot.Error} - */ - interface UnhandledAlertError extends webdriver.error.Error { - //region Methods - - /** - * @return {string} The text displayed with the unhandled alert. - */ - getAlertText(): string; - - /** - * @return {!webdriver.Alert} The open alert. - * @deprecated Use {@link #getAlertText}. This method will be removed in - * 2.45.0. - */ - getAlert(): Alert; - - - //endregion + /** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ + class UnhandledAlertError extends webdriver.error.UnexpectedAlertOpenError { } /** @@ -2630,7 +3573,9 @@ declare namespace webdriver { interface IBrowser { ANDROID: string; CHROME: string; + EDGE: string; FIREFOX: string; + IE: string; INTERNET_EXPLORER: string; IPAD: string; IPHONE: string; @@ -2651,6 +3596,45 @@ declare namespace webdriver { 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 @@ -2664,15 +3648,45 @@ declare namespace webdriver { //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 @@ -2705,6 +3719,12 @@ declare namespace webdriver { */ 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. @@ -2735,6 +3755,17 @@ declare namespace webdriver { */ 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. @@ -2753,6 +3784,16 @@ declare namespace webdriver { */ 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}. @@ -2760,17 +3801,37 @@ declare namespace webdriver { * desired logging preferences. * @return {!Builder} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Builder; - setLoggingPrefs(prefs: { [key: string]: string }): Builder; + 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 {!webdriver.ProxyConfig} config The configuration to use. + * @param {!capabilities.ProxyConfig} config The configuration to use. * @return {!Builder} A self reference. */ - setProxy(config: ProxyConfig): Builder; + 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. @@ -2793,6 +3854,16 @@ declare namespace webdriver { */ 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. @@ -2800,12 +3871,149 @@ declare namespace webdriver { * capabilities for a new session. * @return {!Builder} A self reference. */ - withCapabilities(capabilities: Capabilities): Builder; - withCapabilities(capabilities: any): Builder; + 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} @@ -2876,7 +4084,7 @@ declare namespace webdriver { SECURE_SSL: string; /** Whether the driver supports manipulating the app cache. */ - SUPPORTS_APPLICATION_CACHE: string; + SUPPORTS_APPLICATION_CACHE: string; /** Whether the driver supports locating elements with CSS selectors. */ SUPPORTS_CSS_SELECTORS: string; @@ -2910,8 +4118,7 @@ declare namespace webdriver { * capabilities to merge into this instance. * @constructor */ - constructor(opt_other?: Capabilities); - constructor(opt_other?: any); + constructor(opt_other?: Capabilities|Object); //endregion @@ -2927,8 +4134,7 @@ declare namespace webdriver { * merge into this instance. * @return {!webdriver.Capabilities} A self reference. */ - merge(other: Capabilities): Capabilities; - merge(other: any): Capabilities; + merge(other: Capabilities|Object): Capabilities; /** * @param {string} key The capability to set. @@ -2946,9 +4152,7 @@ declare namespace webdriver { * logging preferences. * @return {!webdriver.Capabilities} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Capabilities; - setLoggingPrefs(prefs: { [key: string]: string }): Capabilities; - + setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Capabilities; /** * Sets the proxy configuration for this instance. @@ -3010,6 +4214,11 @@ declare namespace webdriver { */ 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. */ @@ -3183,6 +4392,8 @@ declare namespace webdriver { GET_AVAILABLE_LOG_TYPES: string; GET_LOG: string; GET_SESSION_LOGS: string; + + UPLOAD_FILE: string; } var CommandName: ICommandName; @@ -3241,19 +4452,47 @@ declare namespace webdriver { } /** - * Handles the execution of {@code webdriver.Command} objects. + * Handles the execution of WebDriver {@link Command commands}. + * @interface */ - interface CommandExecutor { - /** - * 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 - * {@link bot.response.ResponseObject} object. - * @param {!webdriver.Command} command The command to execute. - * @param {function(Error, !bot.response.ResponseObject=)} callback the function - * to invoke when the command response is ready. - */ - execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; + 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); } /** @@ -3283,39 +4522,42 @@ declare namespace webdriver { /** * 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 {!Array.<{fn: !Function, oneshot: boolean, - * scope: (Object|undefined)}>} The registered listeners for - * the given event type. + * @return {!Set} The registered listeners for the given event + * type. */ - listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: any;}>; + listeners(type: string): any; /** * Registers a listener. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn 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. + * @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, listenerFn: Function, opt_scope?:any): EventEmitter; + 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} listenerFn The function to invoke when the event is fired. + * @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, listenerFn: any, opt_scope?: any): EventEmitter; + 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} listenerFn The function to invoke when the event is fired. + * @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, listenerFn: Function, opt_scope?:any): EventEmitter; + on(type: string, fn: Function, opt_scope?:any): EventEmitter; /** * Removes a previously registered event listener. @@ -3340,14 +4582,20 @@ declare namespace webdriver { /** * Interface for navigating back and forth in the browser history. */ - interface WebDriverNavigation { + class Navigation { //region Constructors /** - * @param {!webdriver.WebDriver} driver The parent driver. - * @constructor + * 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() */ - new (driver: WebDriver): WebDriverNavigation; + constructor(driver: WebDriver); //endregion @@ -3397,14 +4645,14 @@ declare namespace webdriver { /** * Provides methods for managing browser and driver state. */ - interface WebDriverOptions { + class Options { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: webdriver.WebDriver): WebDriverOptions; + constructor(driver: webdriver.WebDriver); //endregion @@ -3417,13 +4665,13 @@ declare namespace webdriver { * @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 {!webdriver.promise.Promise} A promise that will be resolved when the - * cookie has been added to the page. + * @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): webdriver.promise.Promise; - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; + 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. @@ -3467,19 +4715,19 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Logs} The interface for managing driver * logs. */ - logs(): WebDriverLogs; + logs(): webdriver.Logs; /** * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver * timeouts. */ - timeouts(): WebDriverTimeouts; + timeouts(): webdriver.Timeouts; /** * @return {!webdriver.WebDriver.Window} The interface for managing the * current window. */ - window(): WebDriverWindow; + window(): webdriver.Window; //endregion } @@ -3487,14 +4735,14 @@ declare namespace webdriver { /** * An interface for managing timeout behavior for WebDriver instances. */ - interface WebDriverTimeouts { + class Timeouts { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverTimeouts; + constructor(driver: webdriver.WebDriver); //endregion @@ -3549,7 +4797,7 @@ declare namespace webdriver { /** * An interface for managing the current window. */ - interface WebDriverWindow { + class Window { //region Constructors @@ -3557,7 +4805,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverWindow; + constructor(driver: webdriver.WebDriver); //endregion @@ -3612,7 +4860,7 @@ declare namespace webdriver { /** * Interface for managing WebDriver log records. */ - interface WebDriverLogs { + class Logs { //region Constructors @@ -3620,7 +4868,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverLogs; + constructor(driver: webdriver.WebDriver); //endregion @@ -3640,7 +4888,7 @@ declare namespace webdriver { * promise that will resolve to a list of log entries for the specified * type. */ - get(type: string): webdriver.promise.Promise; + get(type: webdriver.logging.Type): webdriver.promise.Promise; /** * Retrieves the log types available to this driver. @@ -3655,7 +4903,7 @@ declare namespace webdriver { /** * An interface for changing the focus of the driver to another frame or window. */ - interface WebDriverTargetLocator { + class TargetLocator { //region Constructors @@ -3663,7 +4911,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverTargetLocator; + constructor(driver: webdriver.WebDriver); //endregion @@ -3687,44 +4935,47 @@ declare namespace webdriver { /** * Schedules a command to switch the focus of all future commands to another - * frame on the page. - *

    - * If the frame is specified by a number, the command will switch to the frame - * by its (zero-based) index into the {@code window.frames} collection. - *

    - * If the frame is specified by a string, the command will select the frame by - * its name or ID. To select sub-frames, simply separate the frame names/IDs by - * dots. As an example, "main.child" will select the frame with the name "main" - * and then its child "child". - *

    - * If the specified frame can not be found, the deferred result will errback - * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. - * @param {string|number} nameOrIndex The frame locator. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the specified frame. + * 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: string): webdriver.promise.Promise; - frame(nameOrIndex: number): webdriver.promise.Promise; + 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 {@code webdriver.WebDriver#getWindowHandles}). - *

    - * If the specificed window can not be found, the deferred result will errback - * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. + * 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 {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the specified window. + * @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 alert dialog. This command - * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal - * dialog is not currently open. - * @return {!webdriver.Alert} The open alert. + * 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; @@ -3789,27 +5040,14 @@ declare namespace webdriver { //region Constructors /** - * @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a + * @param {!(Session|promise.Promise)} session Either a * known session or a promise that will be resolved to a session. - * @param {!webdriver.CommandExecutor} executor The executor to use when - * sending commands to the browser. - * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * @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 */ - constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - - //endregion - - //region Static Properties - - static Navigation: WebDriverNavigation; - static Options: WebDriverOptions; - static Timeouts: WebDriverTimeouts; - static Window: WebDriverWindow; - static Logs: WebDriverLogs; - static TargetLocator: WebDriverTargetLocator; + constructor(session: Session|webdriver.promise.Promise, executor: Executor, opt_flow?: webdriver.promise.ControlFlow); //endregion @@ -3817,29 +5055,29 @@ declare namespace webdriver { /** * Creates a new WebDriver client for an existing session. - * @param {!webdriver.CommandExecutor} executor Command executor to use when - * querying for session details. + * @param {!command.Executor} executor Command executor to use when querying + * for session details. * @param {string} sessionId ID of the session to attach to. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver - * commands should execute under. Defaults to the - * {@link webdriver.promise.controlFlow() currently active} control flow. - * @return {!webdriver.WebDriver} A new client for the specified session. + * @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: CommandExecutor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static attachToSession(executor: Executor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; /** * Creates a new WebDriver session. - * @param {!webdriver.CommandExecutor} executor The executor to create the new - * session with. - * @param {!webdriver.Capabilities} desiredCapabilities The desired + * @param {!command.Executor} executor The executor to create the new session + * with. + * @param {!./capabilities.Capabilities} desiredCapabilities The desired * capabilities for the new session. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * @param {promise.ControlFlow=} opt_flow The control flow all driver * commands should execute under, including the initial session creation. - * Defaults to the {@link webdriver.promise.controlFlow() currently active} + * Defaults to the {@link promise.controlFlow() currently active} * control flow. - * @return {!webdriver.WebDriver} The driver for the newly created session. + * @return {!WebDriver} The driver for the newly created session. */ - static createSession(executor: CommandExecutor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; //endregion @@ -3852,20 +5090,22 @@ declare namespace webdriver { controlFlow(): webdriver.promise.ControlFlow; /** - * Schedules a {@code webdriver.Command} to be executed by this driver's - * {@code webdriver.CommandExecutor}. - * @param {!webdriver.Command} command The command to schedule. + * 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 {!webdriver.promise.Promise} A promise that will be resolved with - * the command result. + * @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 webdriver.FileDetector file detector} that should be + * Sets the {@linkplain input.FileDetector file detector} that should be * used with this instance. - * @param {webdriver.FileDetector} detector The detector to use or {@code null}. + * @param {input.FileDetector} detector The detector to use or {@code null}. */ setFileDetector(detector: FileDetector): void; @@ -3895,23 +5135,23 @@ declare namespace webdriver { /** * Creates a new action sequence using this driver. The sequence will not be - * scheduled for execution until {@link webdriver.ActionSequence#perform} is + * scheduled for execution until {@link actions.ActionSequence#perform} is * called. Example: - *

    
    -         *   driver.actions().
    -         *       mouseDown(element1).
    -         *       mouseMove(element2).
    -         *       mouseUp().
    -         *       perform();
    -         * 
    - * @return {!webdriver.ActionSequence} A new action sequence for this instance. + * + * 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 webdriver.TouchSequence#perform} is + * scheduled for execution until {@link actions.TouchSequence#perform} is * called. Example: * * driver.touchActions(). @@ -3919,7 +5159,7 @@ declare namespace webdriver { * doubleTap(element2). * perform(); * - * @return {!webdriver.TouchSequence} A new touch sequence for this instance. + * @return {!actions.TouchSequence} A new touch sequence for this instance. */ touchActions(): TouchSequence; @@ -3961,8 +5201,7 @@ declare namespace webdriver { * scripts return value. * @template T */ - executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; - executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute asynchronous JavaScript in the context of the @@ -4179,38 +5418,27 @@ declare namespace webdriver { * 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 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: + * 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 webdriver.promise.filter(links, function(link) { - * return links.isDisplayed(); - * }).then(function(visibleLinks) { - * return visibleLinks[0]; + * return promise.filter(links, function(link) { + * return link.isDisplayed(); * }); * } * - * When running in the browser, a WebDriver cannot manipulate DOM elements - * directly; it may do so only through a {@link webdriver.WebElement} reference. - * This function may be used to generate a WebElement from a DOM element. A - * reference to the DOM element will be stored in a known location and this - * driver will attempt to retrieve it through {@link #executeScript}. If the - * element cannot be found (eg, it belongs to a different document than the - * one this instance is currently focused on), a - * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The - * locator to use. - * @return {!webdriver.WebElement} A WebElement that can be used to issue + * @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(locatorOrElement: Locator|By.Hash|WebElement|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if an element is present on the page. @@ -4219,35 +5447,36 @@ declare namespace webdriver { * 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 {!(webdriver.Locator|webdriver.By.Hash|Element| - * Function)} locatorOrElement The locator to use, or the actual - * DOM element to be located by the server. - * @return {!webdriver.promise.Promise.} A promise that will resolve + * @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: Locator|By.Hash|WebElement|Function): webdriver.promise.Promise; + isElementPresent(locatorOrElement: By|Function): webdriver.promise.Promise; /** * Schedule a command to search for multiple elements on the page. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * strategy to use when searching for the element. - * @return {!webdriver.promise.Promise.>} A + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + 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 screenshot of the entire display containing the browser - *
    * - * @return {!webdriver.promise.Promise.} A promise that will be + * 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; @@ -4256,45 +5485,25 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Options} The options interface for this * instance. */ - manage(): WebDriverOptions; + manage(): webdriver.Options; /** * @return {!webdriver.WebDriver.Navigation} The navigation interface for this * instance. */ - navigate(): WebDriverNavigation; + navigate(): Navigation; /** * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for * this instance. */ - switchTo(): WebDriverTargetLocator; + switchTo(): webdriver.TargetLocator; //endregion } interface IWebElementId { - ELEMENT: string; - } - - /** - * 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; + [ELEMENT:string]: string; } /** @@ -4554,7 +5763,7 @@ declare namespace webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator|By.Hash|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this @@ -4565,7 +5774,7 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. */ - isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + isElementPresent(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that @@ -4576,10 +5785,9 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; } - /** * Defines an object that can be asynchronously serialized to its WebDriver * wire representation. @@ -4600,7 +5808,6 @@ declare namespace webdriver { 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 @@ -4626,35 +5833,59 @@ declare namespace webdriver { */ class WebElement implements Serializable { /** - * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this - * element. - * @param {!(webdriver.promise.Promise.| - * webdriver.WebElement.Id)} id The server-assigned opaque ID for the - * underlying DOM element. - * @constructor + * @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, id: webdriver.promise.Promise|IWebElementId); + constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise|string); /** - * Wire protocol definition of a WebElement ID. - * @typedef {{ELEMENT: string}} - * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * @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 Id: IWebElementId; + static buildId(id: string, opt_noLegacy?: boolean): Object; /** - * The property key used in the wire protocol to indicate that a JSON object - * contains the ID of a WebElement. - * @type {string} - * @const + * 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 ELEMENT_KEY: string; + 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; + 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 @@ -4688,35 +5919,40 @@ declare namespace webdriver { * }); * } * - * @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 + * @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: Locator|By.Hash|Function): WebElementPromise; + 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 + * @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: Locator|By.Hash|Function): webdriver.promise.Promise; + 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 + * @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: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to click on this element. @@ -4727,7 +5963,7 @@ declare namespace webdriver { /** * Schedules a command to type a sequence on the DOM element represented by this - * instance. + * 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 @@ -4799,7 +6035,7 @@ declare namespace webdriver { * * @param {string} cssStyleProperty The name of the CSS style property to look * up. - * @return {!webdriver.promise.Promise.} A promise that will be + * @return {!promise.Promise} A promise that will be * resolved with the requested CSS value. */ getCssValue(cssStyleProperty: string): webdriver.promise.Promise; @@ -4885,10 +6121,10 @@ declare namespace webdriver { 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 + * 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 {!webdriver.promise.Promise.} A promise that will be resolved + * @return {!promise.Promise} A promise that will be resolved * when the element has been cleared. */ clear(): webdriver.promise.Promise; @@ -4900,6 +6136,18 @@ declare namespace webdriver { */ 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 @@ -4907,25 +6155,6 @@ declare namespace webdriver { */ 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; - - /** - * Returns the raw ID string ID for this element. - * @return {!webdriver.promise.Promise} A promise that resolves to this - * element's raw ID as a string value. - * @package - */ - getRawId(): webdriver.promise.Promise; - - /** @override */ - serialize(): 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 @@ -4933,14 +6162,8 @@ declare namespace webdriver { */ getInnerHtml(): webdriver.promise.Promise; - /** - * Compares to WebElements for equality. - * @param {!webdriver.WebElement} a A WebElement. - * @param {!webdriver.WebElement} b A WebElement. - * @return {!webdriver.promise.Promise} A promise that will be resolved to - * whether the two WebElements are equal. - */ - static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; + /** @override */ + serialize(): webdriver.promise.Promise; } /** @@ -4966,6 +6189,14 @@ declare namespace webdriver { * @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. @@ -5075,191 +6306,31 @@ declare namespace webdriver { * @template R */ thenFinally(callback: () => any): webdriver.promise.Promise; - } - namespace By { /** - * Locates elements that have a specific class name. The returned locator - * is equivalent to searching for elements with the CSS selector ".clazz". + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: * - * @param {string} className The class name to search for. - * @return {!webdriver.Locator} 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 - */ - function className(value: string): Locator; - - /** - * Locates elements using a CSS selector. For browsers that do not support - * CSS selectors, WebDriver implementations may return an - * {@linkplain bot.Error.State.INVALID_SELECTOR invalid selector} error. An - * implementation may, however, emulate the CSS selector API. + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {string} selector The CSS selector to use. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/CSS2/selector.html - */ - function css(value: string): Locator; - - /** - * Locates an element by its ID. + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); * - * @param {string} id The ID to search for. - * @return {!webdriver.Locator} The new locator. + * @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 */ - function id(value: string): Locator; - - /** - * Locates link elements whose {@linkplain webdriver.WebElement#getText visible - * text} matches the given string. - * - * @param {string} text The link text to search for. - * @return {!webdriver.Locator} The new locator. - */ - function linkText(value: string): Locator; - - /** - * 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): !webdriver.promise.Promise} A new, - * JavaScript-based locator function. - */ - function js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; - - /** - * Locates elements whose {@code name} attribute has the given value. - * - * @param {string} name The name attribute to search for. - * @return {!webdriver.Locator} The new locator. - */ - function name(value: string): Locator; - - /** - * 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 {!webdriver.Locator} The new locator. - */ - function partialLinkText(value: string): Locator; - - /** - * Locates elements with a given tag name. The returned locator is - * equivalent to using the - * [getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) - * DOM function. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html - */ - function tagName(value: string): Locator; - - /** - * 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 {@code "//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 {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/xpath/ - */ - function xpath(value: string): Locator; - - /** - * 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 Hash = {className: string}| - {css: string}| - {id: string}| - {js: string}| - {linkText: string}| - {name: string}| - {partialLinkText: string}| - {tagName: string}| - {xpath: string}; - } - - /** - * An element locator. - */ - class Locator { - /** - * An element locator. - * @param {string} using The type of strategy to use for this locator. - * @param {string} value The search target of this locator. - * @constructor - */ - constructor(using: string, value: string); - - - /** - * Maps {@link webdriver.By.Hash} keys to the appropriate factory function. - * @type {!Object.} - * @const - */ - static Strategy: { - className: typeof webdriver.By.className; - css: typeof webdriver.By.css; - id: typeof webdriver.By.id; - js: typeof webdriver.By.js; - linkText: typeof webdriver.By.linkText; - name: typeof webdriver.By.name; - partialLinkText: typeof webdriver.By.partialLinkText; - tagName: typeof webdriver.By.tagName; - xpath: typeof webdriver.By.xpath; - }; - - /** - * Verifies that a {@code value} is a valid locator to use for searching for - * elements on the page. - * - * @param {*} value The value to check is a valid locator. - * @return {!(webdriver.Locator|Function)} A valid locator object or function. - * @throws {TypeError} If the given value is an invalid locator. - */ - static checkLocator(value: any): Locator | Function; - - /** - * The search strategy to use when searching for an element. - * @type {string} - */ - using: string; - - /** - * The search target for this locator. - * @type {string} - */ - value: string; - - /** @return {string} String representation of this locator. */ - toString(): string; + catch(errback: Function): webdriver.promise.Promise; } /** @@ -5275,8 +6346,7 @@ declare namespace webdriver { * capabilities. * @constructor */ - constructor(id: string, capabilities: Capabilities); - constructor(id: string, capabilities: any); + constructor(id: string, capabilities: Capabilities|Object); //endregion @@ -5290,7 +6360,7 @@ declare namespace webdriver { /** * @return {!webdriver.Capabilities} This session's capabilities. */ - getCapabilities(): Capabilities; + getCapabilities(): webdriver.Capabilities; /** * Retrieves the value of a specific capability. @@ -5376,10 +6446,6 @@ declare module 'selenium-webdriver/chrome' { export = chrome; } -declare module 'selenium-webdriver/firefox' { - export = firefox; -} - declare module 'selenium-webdriver/executors' { export = executors; } diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 1ab39ba02a..345a8efc5b 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -3,7 +3,7 @@ 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()); + driver = new chrome.Driver(webdriver.Capabilities.chrome(), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -31,6 +31,7 @@ function TestChromeOptions() { options = options.setUserPreferences("preferences"); var capabilities: webdriver.Capabilities = options.toCapabilities(); capabilities = options.toCapabilities(webdriver.Capabilities.chrome()); + var values: chrome.IOptionsValues = options.toJSON(); } function TestServiceBuilder() { @@ -51,7 +52,7 @@ function TestServiceBuilder() { function TestChromeModule() { var service: any = chrome.getDefaultService(); - chrome.setDefaultService(new remote.DriverService('executable', new chrome.Options())); + chrome.setDefaultService({}); } function TestBinary() { @@ -65,8 +66,8 @@ function TestBinary() { 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()); + driver = new chrome.Driver(webdriver.Capabilities.firefox()); + driver = new chrome.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -81,6 +82,7 @@ function TestFirefoxOptions() { options = options.setProfile(new firefox.Profile()); options = options.setProxy({ proxyType: "proxy" }); var capabilities: webdriver.Capabilities = options.toCapabilities(); + var capabilities: webdriver.Capabilities = options.toCapabilities({}); } function TestFirefoxProfile() { @@ -106,7 +108,7 @@ function TestFirefoxProfile() { } function TestExecutors() { - var exec: webdriver.Executor = executors.createExecutor("url"); + var exec: webdriver.CommandExecutor = executors.createExecutor("url"); var promise: webdriver.promise.Promise; exec = executors.createExecutor(promise); } @@ -142,9 +144,7 @@ function TestActionSequence() { 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); + var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); // Click sequence = sequence.click(); @@ -187,6 +187,7 @@ function TestActionSequence() { // SendKeys sequence = sequence.sendKeys("A", "B", "C"); + sequence = sequence.sendKeys(["A", "B", "C"]); sequence.perform().then(function () { }); } @@ -195,7 +196,7 @@ function TestTouchSequence() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); var sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver); @@ -318,9 +319,9 @@ function TestCommand() { command = command.setParameters({ param: 123 }); } -function TestDeferredExecutor() { - var promise: webdriver.promise.Promise; - var executor: webdriver.DeferredExecutor = new webdriver.DeferredExecutor(promise); +function TestCommandExecutor() { + var c: webdriver.CommandExecutor = { execute: function (command: webdriver.Command, callback: (error: Error, obj: any) => any) { } }; + c.execute(new webdriver.Command('name'), function (error: Error, response: any) { }); } function TestCommandName() { @@ -457,7 +458,7 @@ function TestEventEmitter() { } function TestKey() { - var key: webdriver.Key; + var key: string; key = webdriver.Key.ADD; key = webdriver.Key.ALT; @@ -519,15 +520,35 @@ function TestKey() { key = webdriver.Key.SUBTRACT; key = webdriver.Key.TAB; key = webdriver.Key.UP; + + key = webdriver.Key.chord(webdriver.Key.NUMPAD0, webdriver.Key.NUMPAD1); } -function TestBy() { +function TestLocator() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.By = new webdriver.By('class name', 'class'); + var locator: webdriver.Locator = new webdriver.Locator('class name', 'class'); + var locatorOrFn: webdriver.Locator|Function; + + locatorOrFn = webdriver.Locator.Strategy.className; + locatorOrFn = webdriver.Locator.Strategy.css; + locatorOrFn = webdriver.Locator.Strategy.id; + locatorOrFn = webdriver.Locator.Strategy.js; + locatorOrFn = webdriver.Locator.Strategy.linkText; + locatorOrFn = webdriver.Locator.Strategy.name; + locatorOrFn = webdriver.Locator.Strategy.partialLinkText; + locatorOrFn = webdriver.Locator.Strategy.tagName; + locatorOrFn = webdriver.Locator.Strategy.xpath; + + locatorOrFn = webdriver.Locator.checkLocator(locator); + locatorOrFn = webdriver.Locator.checkLocator({ className: 'class' }); + locatorOrFn = webdriver.Locator.checkLocator(Error); + + var using: string = locator.using; + var value: string = locator.value; var str: string = locator.toString(); locator = webdriver.By.className('class'); @@ -542,7 +563,7 @@ function TestBy() { // Can import "By" without import declarations var By = webdriver.By; - var locatorHash: webdriver.ByHash; + var locatorHash: webdriver.By.Hash; locatorHash = { className: 'class' }; locatorHash = { css: 'css' }; locatorHash = { id: 'id' }; @@ -570,7 +591,9 @@ function TestSession() { function TestUnhandledAlertError() { var someFunc = function (error: webdriver.UnhandledAlertError) { - var baseError: Error = error; + var baseError: webdriver.error.Error = error; + + var alert: webdriver.Alert = error.getAlert(); var str: string = error.getAlertText(); str = error.toString(); } @@ -591,7 +614,7 @@ function TestWebDriverLogs() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var logs: webdriver.Logs = new webdriver.Logs(driver); + var logs: webdriver.WebDriverLogs = new webdriver.WebDriver.Logs(driver); logs.get(webdriver.logging.Type.BROWSER).then(function (entries: webdriver.logging.Entry[]) { });; logs.getAvailableLogTypes().then(function (types: string[]) { }); @@ -602,7 +625,7 @@ function TestWebDriverNavigation() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var navigation: webdriver.Navigation = new webdriver.Navigation(driver); + var navigation: webdriver.WebDriverNavigation = new webdriver.WebDriver.Navigation(driver); navigation.back().then(function () { }); navigation.forward().then(function () { }); @@ -615,7 +638,7 @@ function TestWebDriverOptions() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var options: webdriver.Options = new webdriver.Options(driver); + var options: webdriver.WebDriverOptions = new webdriver.WebDriver.Options(driver); var promise: webdriver.promise.Promise; // Add Cookie @@ -631,9 +654,9 @@ function TestWebDriverOptions() { 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(); + var logs: webdriver.WebDriverLogs = options.logs(); + var timeouts: webdriver.WebDriverTimeouts = options.timeouts(); + var window: webdriver.WebDriverWindow = options.window(); } function TestWebDriverTargetLocator() { @@ -641,12 +664,13 @@ function TestWebDriverTargetLocator() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.TargetLocator = new webdriver.TargetLocator(driver); + var locator: webdriver.WebDriverTargetLocator = new webdriver.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('name'); promise = locator.frame(1); promise = locator.window('nameOrHandle'); } @@ -656,7 +680,7 @@ function TestWebDriverTimeouts() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var timeouts: webdriver.Timeouts = new webdriver.Timeouts(driver); + var timeouts: webdriver.WebDriverTimeouts = new webdriver.WebDriver.Timeouts(driver); var promise: webdriver.promise.Promise; promise = timeouts.implicitlyWait(123); @@ -669,7 +693,7 @@ function TestWebDriverWindow() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var window: webdriver.Window = new webdriver.Window(driver); + var window: webdriver.WebDriverWindow = new webdriver.WebDriver.Window(driver); var locationPromise: webdriver.promise.Promise; var sizePromise: webdriver.promise.Promise; var voidPromise: webdriver.promise.Promise; @@ -684,7 +708,7 @@ function TestWebDriverWindow() { 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 executor: webdriver.CommandExecutor = 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); @@ -722,11 +746,15 @@ function TestWebDriver() { // findElement var element: webdriver.WebElement; element = driver.findElement(webdriver.By.id('ABC')); + element = driver.findElement({id: 'ABC'}); element = driver.findElement(webdriver.By.js('function(){}')); + element = driver.findElement({js: 'function(){}'}); // findElements driver.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); driver.findElements(webdriver.By.js('function(){}')).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements({ js: 'function(){}' }).then(function (elements: webdriver.WebElement[]) { }); voidPromise = driver.get('http://www.google.com'); driver.getAllWindowHandles().then(function (handles: string[]) { }); @@ -738,11 +766,13 @@ function TestWebDriver() { stringPromise = driver.getWindowHandle(); booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); + booleanPromise = driver.isElementPresent({className: 'ABC'}); booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); + booleanPromise = driver.isElementPresent({js: 'function(){}'}); - var options: webdriver.Options = driver.manage(); - var navigation: webdriver.Navigation = driver.navigate(); - var locator: webdriver.TargetLocator = driver.switchTo(); + var options: webdriver.WebDriverOptions = driver.manage(); + var navigation: webdriver.WebDriverNavigation = driver.navigate(); + var locator: webdriver.WebDriverTargetLocator = driver.switchTo(); var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); driver.setFileDetector(fileDetector); @@ -765,7 +795,7 @@ function TestWebDriver() { function TestSerializable() { var serializable: webdriver.Serializable; - var serial: string|webdriver.promise.IThenable = serializable.serialize(); + var serial: string|webdriver.promise.Promise = serializable.serialize(); } function TestWebElement() { @@ -773,10 +803,10 @@ function TestWebElement() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var promise: webdriver.promise.Promise; + var promise: webdriver.promise.Promise; var element: webdriver.WebElement; - element = new webdriver.WebElement(driver, 'elementId'); + element = new webdriver.WebElement(driver, { ELEMENT: 'ID' }); element = new webdriver.WebElement(driver, promise); var voidPromise: webdriver.promise.Promise; @@ -787,8 +817,13 @@ function TestWebElement() { voidPromise = element.click(); element = element.findElement(webdriver.By.id('ABC')); + element = element.findElement({id: 'ABC'}); + element.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + element.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); + booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); + booleanPromise = element.isElementPresent({className: 'ABC'}); stringPromise = element.getAttribute('class'); stringPromise = element.getCssValue('display'); @@ -805,11 +840,14 @@ function TestWebElement() { voidPromise = element.sendKeys('A', 'B', 'C'); voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); voidPromise = element.submit(); - element.getId().then(function (id: string) { }); + element.getId().then(function (id: typeof webdriver.WebElement.Id) { }); element.getRawId().then(function (id: string) { }); - element.serialize().then(function (id: webdriver.IWebElementId) { }); + element.serialize().then(function (id: typeof webdriver.WebElement.Id) { }); - booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); + booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, { ELEMENT: 'ID2' })); + + var id: typeof webdriver.WebElement.Id = webdriver.WebElement.Id; + var key: string = webdriver.WebElement.ELEMENT_KEY; } function TestWebElementPromise() { @@ -839,7 +877,7 @@ function TestLogging() { preferences.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.ALL); var prefs: any = preferences.toJSON(); - var level: webdriver.logging.Level = webdriver.logging.getLevel('OFF'); + var level: webdriver.logging.ILevel = webdriver.logging.getLevel('OFF'); level = webdriver.logging.getLevel(1); level = webdriver.logging.Level.ALL; @@ -849,10 +887,10 @@ function TestLogging() { level = webdriver.logging.Level.SEVERE; level = webdriver.logging.Level.WARNING; - var name: string = level.name(); - var value: number = level.value(); + var name: string = level.name; + var value: number = level.value; - var type: webdriver.logging.Type; + var type: string; type = webdriver.logging.Type.BROWSER; type = webdriver.logging.Type.CLIENT; type = webdriver.logging.Type.DRIVER; @@ -875,6 +913,9 @@ function TestLoggingEntry() { var message: string = entry.message; var timestamp: number = entry.timestamp; var type: string = entry.type; + + entry = webdriver.logging.Entry.fromClosureLogRecord({}); + entry = webdriver.logging.Entry.fromClosureLogRecord({}, webdriver.logging.Type.DRIVER); } function TestPromiseModule() { @@ -905,29 +946,29 @@ function TestPromiseModule() { 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[]) { + var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { return true; }, this); @@ -954,13 +995,26 @@ function TestPromiseModule() { var bool: boolean = webdriver.promise.isGenerator(function () { }); var isPromise: boolean = webdriver.promise.isPromise('ABC'); - stringPromise = webdriver.promise.rejected('{a: 123}'); + voidPromise = 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 TestStacktraceModule() { + var bool: boolean = webdriver.stacktrace.BROWSER_SUPPORTED; + + var frame: webdriver.stacktrace.Frame = new webdriver.stacktrace.Frame(); + var baseFrame: webdriver.stacktrace.Frame = frame; + + var snapshot: webdriver.stacktrace.Snapshot = new webdriver.stacktrace.Snapshot(); + var baseSnapshot: webdriver.stacktrace.Snapshot = snapshot; + + var err: Error = webdriver.stacktrace.format(new Error("Error")); + var frames: webdriver.stacktrace.Frame[] = webdriver.stacktrace.get(); +} + function TestUntilModule() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). @@ -1071,12 +1125,13 @@ function TestPromiseClass() { } function TestThenableClass() { - var thenable: webdriver.promise.Promise = new webdriver.promise.Promise(); + var thenable: webdriver.promise.Thenable = new webdriver.promise.Thenable(); thenable.cancel('Abort'); var isPending: boolean = thenable.isPending(); + thenable = thenable.then(); 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; }); @@ -1089,30 +1144,76 @@ function TestThenableClass() { 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(); + errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE; + errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_VISIBLE; + errorCode = webdriver.error.ErrorCode.IME_ENGINE_ACTIVATION_FAILED; + errorCode = webdriver.error.ErrorCode.IME_NOT_AVAILABLE; + errorCode = webdriver.error.ErrorCode.INVALID_COOKIE_DOMAIN; + errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_COORDINATES; + errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_STATE; + errorCode = webdriver.error.ErrorCode.INVALID_SELECTOR_ERROR; + errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR; + errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPE; + errorCode = webdriver.error.ErrorCode.JAVASCRIPT_ERROR; + errorCode = webdriver.error.ErrorCode.METHOD_NOT_ALLOWED; + errorCode = webdriver.error.ErrorCode.MODAL_DIALOG_OPENED; + errorCode = webdriver.error.ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS; + errorCode = webdriver.error.ErrorCode.NO_MODAL_DIALOG_OPEN; + errorCode = webdriver.error.ErrorCode.NO_SUCH_ELEMENT; + errorCode = webdriver.error.ErrorCode.NO_SUCH_FRAME; + errorCode = webdriver.error.ErrorCode.NO_SUCH_WINDOW; + errorCode = webdriver.error.ErrorCode.SCRIPT_TIMEOUT; + errorCode = webdriver.error.ErrorCode.SESSION_NOT_CREATED; + errorCode = webdriver.error.ErrorCode.SQL_DATABASE_ERROR; + errorCode = webdriver.error.ErrorCode.STALE_ELEMENT_REFERENCE; + errorCode = webdriver.error.ErrorCode.SUCCESS; + errorCode = webdriver.error.ErrorCode.TIMEOUT; + errorCode = webdriver.error.ErrorCode.UNABLE_TO_SET_COOKIE; + errorCode = webdriver.error.ErrorCode.UNKNOWN_COMMAND; + errorCode = webdriver.error.ErrorCode.UNKNOWN_ERROR; + errorCode = webdriver.error.ErrorCode.UNSUPPORTED_OPERATION; + errorCode = webdriver.error.ErrorCode.XPATH_LOOKUP_ERROR; +} + +function TestError() { + var error: webdriver.error.Error; + + error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE); + error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE, 'Message'); + + var code: number = error.code; + var state: string = error.state; + var message: string = error.message; + var name: string = error.name; + var stack: string = error.stack; + var isAutomationError: boolean = error.isAutomationError; + var errorStr: string = error.toString(); + + state = webdriver.error.Error.State.ELEMENT_NOT_SELECTABLE + state = webdriver.error.Error.State.ELEMENT_NOT_VISIBLE; + state = webdriver.error.Error.State.IME_ENGINE_ACTIVATION_FAILED; + state = webdriver.error.Error.State.IME_NOT_AVAILABLE; + state = webdriver.error.Error.State.INVALID_COOKIE_DOMAIN; + state = webdriver.error.Error.State.INVALID_ELEMENT_COORDINATES; + state = webdriver.error.Error.State.INVALID_ELEMENT_STATE; + state = webdriver.error.Error.State.INVALID_SELECTOR; + state = webdriver.error.Error.State.JAVASCRIPT_ERROR; + state = webdriver.error.Error.State.MOVE_TARGET_OUT_OF_BOUNDS; + state = webdriver.error.Error.State.NO_SUCH_ALERT; + state = webdriver.error.Error.State.NO_SUCH_DOM + state = webdriver.error.Error.State.NO_SUCH_ELEMENT; + state = webdriver.error.Error.State.NO_SUCH_FRAME; + state = webdriver.error.Error.State.NO_SUCH_WINDOW; + state = webdriver.error.Error.State.SCRIPT_TIMEOUT; + state = webdriver.error.Error.State.SESSION_NOT_CREATED; + state = webdriver.error.Error.State.STALE_ELEMENT_REFERENCE; + state = webdriver.error.Error.State.SUCCESS; + state = webdriver.error.Error.State.TIMEOUT; + state = webdriver.error.Error.State.UNABLE_TO_SET_COOKIE; + state = webdriver.error.Error.State.UNEXPECTED_ALERT_OPEN + state = webdriver.error.Error.State.UNKNOWN_COMMAND; + state = webdriver.error.Error.State.UNKNOWN_ERROR; + state = webdriver.error.Error.State.UNSUPPORTED_OPERATION; } function TestTestingModule() { diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index b3afe098ac..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.53.1 -// Project: https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver -// Definitions by: Bill Armstrong , Yuki Kokubun +// Type definitions for Selenium WebDriverJS 2.44.0 +// Project: https://code.google.com/p/selenium/ +// Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace chrome { @@ -19,7 +19,8 @@ declare namespace chrome { * {@code null} to use the currently active flow. * @constructor */ - constructor(opt_config?: Options|webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: webdriver.Capabilities, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: Options, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); } interface IOptionsValues { @@ -239,53 +240,6 @@ declare namespace chrome { 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. @@ -301,6 +255,21 @@ declare namespace chrome { * @return {!webdriver.Capabilities} The capabilities. */ toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; + + + /** + * Converts this instance to its JSON wire protocol representation. Note this + * function is an implementation not intended for general use. + * @return {{args: !Array., + * binary: (string|undefined), + * detach: boolean, + * extensions: !Array., + * localState: (Object|undefined), + * logFile: (string|undefined), + * prefs: (Object|undefined)}} The JSON wire protocol representation + * of this instance. + */ + toJSON(): IOptionsValues; } /** @@ -379,7 +348,8 @@ declare namespace chrome { * configuration to use. * @return {!ServiceBuilder} A self reference. */ - setStdio(config: string|Array): ServiceBuilder; + setStdio(config: string): ServiceBuilder; + setStdio(config: any[]): ServiceBuilder; /** @@ -398,7 +368,7 @@ declare namespace chrome { * @throws {Error} If the driver exectuable was not specified and a default * could not be found on the current PATH. */ - build(): remote.DriverService; + build(): any; } /** @@ -407,1325 +377,395 @@ declare namespace chrome { * a ChromeDriver executable found on the system PATH. * @return {!remote.DriverService} The default ChromeDriver service. */ - function getDefaultService(): remote.DriverService; + function getDefaultService(): any; /** * 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; + function setDefaultService(service: any): void; } -declare namespace edge { +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); - 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); + /** + * 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; - /** - * This function is a no-op as file detectors are not supported by this - * implementation. - * @override - */ - setFileDetector(): 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; } /** - * Class for managing MicrosoftEdgeDriver specific options. + * A WebDriver client for Firefox. + * + * @extends {webdriver.WebDriver} + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|webdriver.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link webdriver.Capabilities}, or as a raw hash + * object. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + * @constructor + */ + constructor(opt_config?: webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: any, opt_flow?: webdriver.promise.ControlFlow); + } + + /** + * Configuration options for the FirefoxDriver. */ class Options { + /** + * @constructor + */ + constructor(); - /** - * 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 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): Options; + setProfile(profile: Profile): 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; + /** + * 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): Options; + setBinary(binary: Binary): 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; + + /** + * Sets the logging preferences for the new session. + * @param {webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + + /** + * Sets the proxy to use. + * + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts these options to a {@link webdriver.Capabilities} instance. + * + * @return {!webdriver.Capabilities} A new capabilities object. + */ + toCapabilities(opt_remote?: any): webdriver.Capabilities; } /** - * Creates {@link remote.DriverService} instances that manage a - * MicrosoftEdgeDriver server in a child process. + * 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 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); + 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); - /** - * 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; + /** + * 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 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; + /** + * 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; - /** - * 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 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; } - - /** - * 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. + * @param url The server's URL, or a promise that will resolve to that URL. + * @returns {!webdriver.CommandExecutor} 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); - - } + function createExecutor(url: string): webdriver.CommandExecutor; + function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; } declare namespace webdriver { namespace error { - class IError extends Error { - constructor(opt_error?: string); + interface IErrorCode { + SUCCESS: number; - code(): number; + NO_SUCH_ELEMENT: number; + NO_SUCH_FRAME: number; + UNKNOWN_COMMAND: number; + UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. + STALE_ELEMENT_REFERENCE: number; + ELEMENT_NOT_VISIBLE: number; + INVALID_ELEMENT_STATE: number; + UNKNOWN_ERROR: number; + ELEMENT_NOT_SELECTABLE: number; + JAVASCRIPT_ERROR: number; + XPATH_LOOKUP_ERROR: number; + TIMEOUT: number; + NO_SUCH_WINDOW: number; + INVALID_COOKIE_DOMAIN: number; + UNABLE_TO_SET_COOKIE: number; + MODAL_DIALOG_OPENED: number; + UNEXPECTED_ALERT_OPEN: number; + NO_SUCH_ALERT: number; + NO_MODAL_DIALOG_OPEN: number; + SCRIPT_TIMEOUT: number; + INVALID_ELEMENT_COORDINATES: number; + IME_NOT_AVAILABLE: number; + IME_ENGINE_ACTIVATION_FAILED: number; + INVALID_SELECTOR_ERROR: number; + SESSION_NOT_CREATED: number; + MOVE_TARGET_OUT_OF_BOUNDS: number; + SQL_DATABASE_ERROR: number; + INVALID_XPATH_SELECTOR: number; + INVALID_XPATH_SELECTOR_RETURN_TYPE: number; + // The following error codes are derived straight from HTTP return codes. + METHOD_NOT_ALLOWED: 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); - } + var ErrorCode: IErrorCode; /** - * An attempt was made to select an element that cannot be selected. + * Error extension that includes error status codes from the WebDriver wire + * protocol: + * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes + * + * @extends {Error} */ - class ElementNotSelectableError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + class Error { - /** - * 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); - } + //region Constructors - /** - * 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); - } + /** + * @param {!bot.ErrorCode} code The error's status code. + * @param {string=} opt_message Optional error message. + * @constructor + */ + constructor(code: number, opt_message?: 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); - } + //endregion - /** - * 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); - } + //region Static Properties - /** - * 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); - } + /** + * Status strings enumerated in the W3C WebDriver working draft. + * @enum {string} + * @see http://www.w3.org/TR/webdriver/#status-codes + */ + static State: { + ELEMENT_NOT_SELECTABLE: string; + ELEMENT_NOT_VISIBLE: string; + IME_ENGINE_ACTIVATION_FAILED: string; + IME_NOT_AVAILABLE: string; + INVALID_COOKIE_DOMAIN: string; + INVALID_ELEMENT_COORDINATES: string; + INVALID_ELEMENT_STATE: string; + INVALID_SELECTOR: string; + JAVASCRIPT_ERROR: string; + MOVE_TARGET_OUT_OF_BOUNDS: string; + NO_SUCH_ALERT: string; + NO_SUCH_DOM: string; + NO_SUCH_ELEMENT: string; + NO_SUCH_FRAME: string; + NO_SUCH_WINDOW: string; + SCRIPT_TIMEOUT: string; + SESSION_NOT_CREATED: string; + STALE_ELEMENT_REFERENCE: string; + SUCCESS: string; + TIMEOUT: string; + UNABLE_TO_SET_COOKIE: string; + UNEXPECTED_ALERT_OPEN: string; + UNKNOWN_COMMAND: string; + UNKNOWN_ERROR: string; + UNSUPPORTED_OPERATION: string; + }; - /** - * Argument was an invalid selector. - */ - class InvalidSelectorError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //endregion - /** - * 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); - } + //region Properties - /** - * 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); - } + /** + * This error's status code. + * @type {!bot.ErrorCode} + */ + code: number; - /** - * 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); - } + /** @type {string} */ + state: 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); - } + /** @override */ + message: 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); - } + /** @override */ + name: 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); - } + /** @override */ + stack: 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); - } + /** + * Flag used for duck-typing when this code is embedded in a Firefox extension. + * This is required since an Error thrown in one component and then reported + * to another will fail instanceof checks in the second component. + * @type {boolean} + */ + isAutomationError: boolean; - /** - * 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); - } + //endregion - /** - * A new session could not be created. - */ - class SessionNotCreatedError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //region Methods - /** - * 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); - } + /** @return {string} The string representation of this error. */ + toString(): 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); + //endregion } } @@ -1736,97 +776,49 @@ declare namespace webdriver { * @typedef {Object.} */ class Preferences { - setLevel(type: string|Type, level: Level|string|number): void; + setLevel(type: string, level: ILevel): void; toJSON(): { [key: string]: string }; } + interface IType { + /** Logs originating from the browser. */ + BROWSER: string; + /** Logs from a WebDriver client. */ + CLIENT: string; + /** Logs from a WebDriver implementation. */ + DRIVER: string; + /** Logs related to performance. */ + PERFORMANCE: string; + /** Logs from the remote server. */ + SERVER: 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 - } + var Type: IType; /** - * Defines a message level that may be used to control logging output. - * - * @final + * Logging levels. + * @enum {{value: number, name: webdriver.logging.LevelName}} */ - 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; + interface ILevel { + value: number; + name: string; } + interface ILevelValues { + ALL: ILevel; + DEBUG: ILevel; + INFO: ILevel; + WARNING: ILevel; + SEVERE: ILevel; + OFF: ILevel; + } + + var Level: ILevelValues; + /** * 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} @@ -1835,209 +827,75 @@ declare namespace webdriver { * convert . * @return {!webdriver.logging.Level} The converted level. */ - function getLevel(nameOrValue: string|number): Level; + function getLevel(nameOrValue: string): ILevel; + function getLevel(nameOrValue: number): ILevel; interface IEntryJSON { - level: string; - message: string; - timestamp: number; - type: string; + 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; + //region Constructors - /** @type {string} */ - message: string; + /** + * @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: ILevel, message: string, opt_timestamp?:number, opt_type?:string); + constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); - /** @type {number} */ - timestamp: number; + //endregion - /** @type {string} */ - type: string; + //region Public Properties - /** - * @return {{level: string, message: string, timestamp: number, - * type: string}} The JSON representation of this entry. - */ - toJSON(): IEntryJSON; - } + /** @type {!webdriver.logging.Level} */ + level: ILevel; - /** - * 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); + /** @type {string} */ + message: string; - /** @private {string} */ - name_: string; - /** @private {Level} */ - level_: Level; - /** @private {Logger} */ - parent_: Logger; - /** @private {Set} */ - handlers_: any; + /** @type {number} */ + timestamp: number; - /** @return {string} the name of this logger. */ - getName(): string; + /** @type {string} */ + type: 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; + //endregion - /** @return {Level} the log level for this logger. */ - getLevel(): Level; + //region Static Methods - /** - * @return {!Level} the effective level for this logger. - */ - getEffectiveLevel(): Level; + /** + * Converts a {@link goog.debug.LogRecord} into a + * {@link webdriver.logging.Entry}. + * @param {!goog.debug.LogRecord} logRecord The record to convert. + * @param {string=} opt_type The log type. + * @return {!webdriver.logging.Entry} The converted entry. + */ + static fromClosureLogRecord(logRecord: any, opt_type?:string): Entry; - /** - * @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; + //endregion - /** - * 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; + //region Methods - /** - * 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; + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; - /** - * 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; + //endregion } } @@ -2050,15 +908,15 @@ declare namespace webdriver { * input array's promises are rejected, the returned promise will be rejected * with the same reason. * - * @param {!Array<(T|!ManagedPromise)>} arr An array of + * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of * promises to wait on. - * @return {!ManagedPromise>} A promise that is + * @return {!webdriver.promise.Promise.>} 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; + function all(arr: Promise[]): Promise; /** * Invokes the appropriate callback function as soon as a promised @@ -2081,9 +939,9 @@ declare namespace webdriver { * 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 + * @param {function(!webdriver.promise.ControlFlow)} callback The entry point * to the newly created flow. - * @return {!ManagedPromise} A promise that resolves to the callback + * @return {!webdriver.promise.Promise} A promise that resolves to the callback * result. */ function createFlow(callback: (flow: ControlFlow) => R): Promise; @@ -2108,7 +966,7 @@ declare namespace webdriver { * 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. + * @return {!webdriver.promise.Promise} The promise. */ function delayed(ms: number): Promise; @@ -2116,25 +974,26 @@ declare namespace webdriver { * 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 + *

    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 + *

    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 + * @param {!(Array.|webdriver.promise.Promise.>)} 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 + * @param {function(this: SELF, TYPE, number, !Array.): ( + * boolean|webdriver.promise.Promise.)} 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; + function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise; + function filter(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise /** * Creates a new deferred object. @@ -2144,9 +1003,8 @@ declare namespace webdriver { /** * 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 + * @param {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. */ function fulfilled(opt_value?: T): Promise; @@ -2155,44 +1013,42 @@ declare namespace webdriver { * 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 + *

    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 + *

    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 + * @param {!(Array.|webdriver.promise.Promise.>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array): ?} fn The + * @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 + function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function map(arr: Promise, fn: (element: T, index: number, array: T[]) => 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 + * @return {!webdriver.promise.Promise} The rejected promise. */ - function rejected(opt_reason?: any): Promise; + 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 + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes 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. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. * @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 + * @return {!webdriver.promise.Promise} A promise that will be resolved with the * result of the provided function's callback. */ function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; @@ -2203,35 +1059,37 @@ declare namespace webdriver { * 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. + *

    Example 1: the Fibonacci Sequence. + *

    
    +         * webdriver.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
    +         * });
    +         * 
    * - * 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 - * }); + *

    Example 2: a generator that throws. + *

    
    +         * webdriver.promise.consume(function* () {
    +         *   yield webdriver.promise.delayed(250).then(function() {
    +         *     throw Error('boom');
    +         *   });
    +         * }).thenCatch(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 + * @return {!webdriver.promise.Promise.} A promise that will resolve to the * generator's final result. * @throws {TypeError} If the given function is not a generator. */ @@ -2246,9 +1104,10 @@ declare namespace webdriver { * resolved successfully. * @param {Function=} opt_errback The function to call when the value is * rejected. - * @return {!ManagedPromise} A new promise. + * @return {!webdriver.promise.Promise} A new promise. */ - function when(value: T|Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: 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 @@ -2261,19 +1120,19 @@ declare namespace webdriver { * Warning: This function makes no checks against objects that contain * cyclical references: * - * var value = {}; - * value['self'] = value; - * promise.fullyResolved(value); // Stack overflow. + * var value = {}; + * value['self'] = value; + * webdriver.promise.fullyResolved(value); // Stack overflow. * * @param {*} value The value to fully resolve. - * @return {!ManagedPromise} A promise for a fully resolved version + * @return {!webdriver.promise.Promise} 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. + * @param {!webdriver.promise.ControlFlow} flow The new default flow. * @throws {Error} If the default flow is not currently active. */ function setDefaultFlow(flow: ControlFlow): void; @@ -2282,249 +1141,63 @@ declare namespace webdriver { /** * Error used when the computation of a promise is cancelled. + * + * @extends {goog.debug.Error} + * @final */ - class CancellationError extends Error { - /** - * @param {string=} opt_msg The cancellation message. - */ - constructor(opt_msg?: string); + class CancellationError { + /** + * @param {string=} opt_msg The cancellation message. + * @constructor + */ + constructor(opt_msg?: string); + + name: string; + message: 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. + * 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|Error): void; + 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. This function most - * overridden by subtypes. + * 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. + * @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; + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): 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: T) => R, opt_errback?: (error: any) => any): Promise; + /** * Registers a listener for when this promise is rejected. This is synonymous @@ -2552,31 +1225,6 @@ declare namespace webdriver { */ 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 @@ -2617,7 +1265,294 @@ declare namespace webdriver { * with the callback result. * @template R */ - thenFinally(callback: Function): Promise; + thenFinally(callback: () => any): 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 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: T) => Promise, opt_errback?: (error: any) => any): 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: T) => R, opt_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().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 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): 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: webdriver.promise.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 webdriver.promise.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 {promise.ControlFlow=} opt_flow The control flow + * this instance was created under. Defaults to the currently active flow. + * @constructor + */ + 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(reason: any): 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?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * 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?: (value: T) => R, opt_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().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 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): Promise; //endregion } @@ -2856,6 +1791,107 @@ declare namespace webdriver { } } + namespace stacktrace { + /** + * Class representing one stack frame. + */ + class Frame { + /** + * @param {(string|undefined)} context Context object, empty in case of global + * functions or if the browser doesn't provide this information. + * @param {(string|undefined)} name Function name, empty in case of anonymous + * functions. + * @param {(string|undefined)} alias Alias of the function if available. For + * example the function name will be 'c' and the alias will be 'b' if the + * function is defined as a.b = function c() {};. + * @param {(string|undefined)} path File path or URL including line number and + * optionally column number separated by colons. + * @constructor + */ + constructor(context?: string, name?: string, alias?: string, path?: string); + + /** + * @return {string} The function name or empty string if the function is + * anonymous and the object field which it's assigned to is unknown. + */ + getName(): string; + + + /** + * @return {string} The url or empty string if it is unknown. + */ + getUrl(): string; + + + /** + * @return {number} The line number if known or -1 if it is unknown. + */ + getLine(): number; + + + /** + * @return {number} The column number if known and -1 if it is unknown. + */ + getColumn(): number; + + + /** + * @return {boolean} Whether the stack frame contains an anonymous function. + */ + isAnonymous(): boolean; + + + /** + * Converts this frame to its string representation using V8's stack trace + * format: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + * @return {string} The string representation of this frame. + * @override + */ + toString(): string; + } + + /** + * Stores a snapshot of the stack trace at the time this instance was created. + * The stack trace will always be adjusted to exclude this function call. + */ + class Snapshot { + /** + * @param {number=} opt_slice The number of frames to remove from the top of + * the generated stack trace. + * @constructor + */ + constructor(opt_slice?: number); + + /** + * @return {!Array.} The parsed stack trace. + */ + getStacktrace(): Frame[]; + } + + /** + * Formats an error's stack trace. + * @param {!(Error|goog.testing.JsUnitException)} error The error to format. + * @return {!(Error|goog.testing.JsUnitException)} The formatted error. + */ + function format(error: any): any; + + /** + * Gets the native stack trace if available otherwise follows the call chain. + * The generated trace will exclude all frames up to and including the call to + * this function. + * @return {!Array.} The frames of the stack trace. + */ + function get(): Frame[]; + + /** + * Whether the current browser supports stack traces. + * + * @type {boolean} + * @const + */ + var BROWSER_SUPPORTED: boolean; + } + namespace until { /** * Defines a condition to @@ -2879,31 +1915,32 @@ declare namespace webdriver { /** * 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 + * to the designated frame. The target frame may be specified as: + *
      + *
    1. A numeric index into {@code 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. + *
    * - * 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 + *

    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 + * @param {!(number|webdriver.WebElement| + * webdriver.Locator|webdriver.By.Hash| + * function(!webdriver.WebDriver): !webdriver.WebElement)} frame * The frame identifier. - * @return {!Condition} A new condition. + * @return {!until.Condition.} A new condition. */ - function ableToSwitchToFrame(frame: number|WebElement|By|((webdriver: WebDriver)=>WebElement)): Condition; + function ableToSwitchToFrame(frame: number|WebElement|Locator|By.Hash|((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. + * @return {!until.Condition.} The new condition. */ function alertIsPresent(): Condition; @@ -2963,12 +2000,13 @@ declare namespace webdriver { /** * Creates a condition that will loop until an element is - * {@link ./webdriver.WebDriver#findElement found} with the given locator. + * {@link webdriver.WebDriver#findElement found} with the given locator. * - * @param {!(By|Function)} locator The locator to use. + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. * @return {!until.Condition.} The new condition. */ - function elementLocated(locator: By|Function): Condition; + function elementLocated(locator: Locator|By.Hash|Function): Condition; /** * Creates a condition that will wait for the given element's @@ -3001,7 +2039,7 @@ declare namespace webdriver { * * @param {!webdriver.WebElement} element The element to test. * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition} The new condition. + * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#getText */ function elementTextMatches(element: WebElement, regex: RegExp): Condition; @@ -3015,7 +2053,7 @@ declare namespace webdriver { * @return {!until.Condition.>} The new * condition. */ - function elementsLocated(locator: By|Function): Condition; + function elementsLocated(locator: Locator|By.Hash|Function): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -3023,7 +2061,7 @@ declare namespace webdriver { * has loaded. * * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition} The new condition. + * @return {!until.Condition.} The new condition. */ function stalenessOf(element: WebElement): Condition; @@ -3042,7 +2080,7 @@ declare namespace webdriver { * given value. * * @param {string} title The expected page title. - * @return {!until.Condition} The new condition. + * @return {!until.Condition.} The new condition. */ function titleIs(title: string): Condition; @@ -3067,18 +2105,18 @@ declare namespace webdriver { } /** - * 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} + * Enumeration of the buttons used in the advanced interactions API. + * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. + * @enum {number} */ - enum Button { - LEFT, - MIDDLE, - RIGHT, + interface IButton { + LEFT: number; + MIDDLE: number; + RIGHT: number; } + var Button: IButton; + /** * Representations of pressable keys that aren't text. These are stored in * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to @@ -3086,86 +2124,102 @@ declare namespace webdriver { * * @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, + interface IKey { + NULL: string; + CANCEL: string; // ^break + HELP: string; + BACK_SPACE: string; + TAB: string; + CLEAR: string; + RETURN: string; + ENTER: string; + SHIFT: string; + CONTROL: string; + ALT: string; + PAUSE: string; + ESCAPE: string; + SPACE: string; + PAGE_UP: string; + PAGE_DOWN: string; + END: string; + HOME: string; + ARROW_LEFT: string; + LEFT: string; + ARROW_UP: string; + UP: string; + ARROW_RIGHT: string; + RIGHT: string; + ARROW_DOWN: string; + DOWN: string; + INSERT: string; + DELETE: string; + SEMICOLON: string; + EQUALS: string; - NUMPAD0, // number pad keys - NUMPAD1, - NUMPAD2, - NUMPAD3, - NUMPAD4, - NUMPAD5, - NUMPAD6, - NUMPAD7, - NUMPAD8, - NUMPAD9, - MULTIPLY, - ADD, - SEPARATOR, - SUBTRACT, - DECIMAL, - DIVIDE, + NUMPAD0: string; // number pad keys + NUMPAD1: string; + NUMPAD2: string; + NUMPAD3: string; + NUMPAD4: string; + NUMPAD5: string; + NUMPAD6: string; + NUMPAD7: string; + NUMPAD8: string; + NUMPAD9: string; + MULTIPLY: string; + ADD: string; + SEPARATOR: string; + SUBTRACT: string; + DECIMAL: string; + DIVIDE: string; - F1, // function keys - F2, - F3, - F4, - F5, - F6, - F7, - F8, - F9, - F10, - F11, - F12, + F1: string; // function keys + F2: string; + F3: string; + F4: string; + F5: string; + F6: string; + F7: string; + F8: string; + F9: string; + F10: string; + F11: string; + F12: string; - COMMAND, // Apple command key - META // alias for Windows key + COMMAND: string; // Apple command key + META: string; // alias for Windows key + /** + * Simulate pressing many keys at once in a "chord". Takes a sequence of + * {@link webdriver.Key}s or strings, appends each of the values to a string, + * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns + * the resultant string. + * + * Note: when the low-level webdriver key handlers see Keys.NULL, active + * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. + * + * @param {...string} var_args The key sequence to concatenate. + * @return {string} The null-terminated key sequence. + * @see http://code.google.com/p/webdriver/issues/detail?id=79 + */ + chord: (...var_args: string[]) => string; } + var Key: IKey; + /** * 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(); + *

    Example:

    
    +     *   new webdriver.ActionSequence(driver).
    +     *       keyDown(webdriver.Key.SHIFT).
    +     *       click(element1).
    +     *       click(element2).
    +     *       dragAndDrop(element3, element4).
    +     *       keyUp(webdriver.Key.SHIFT).
    +     *       perform();
    +     * 
    * */ class ActionSequence { @@ -3193,18 +2247,14 @@ declare namespace webdriver { * 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. + * @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 An optional offset, in pixels. + * Defaults to (0, 0). + * @return {!webdriver.ActionSequence} A self reference. */ - mouseMove(location: WebElement|ILocation, opt_offset?: ILocation): ActionSequence; + mouseMove(location: WebElement, opt_offset?: ILocation): ActionSequence; + mouseMove(location: ILocation): ActionSequence; /** * Presses a mouse button. The mouse button will not be released until @@ -3212,101 +2262,100 @@ declare namespace webdriver { * 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 + *

    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()
    * - * sequence.mouseMove(element).mouseDown() + *

    Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 * - * 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 + * @param {(webdriver.WebElement|webdriver.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 + * Defaults to {@link webdriver.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 + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!ActionSequence} A self reference. + * @return {!webdriver.ActionSequence} A self reference. */ - mouseDown(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + mouseDown(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + mouseDown(opt_elementOrButton?: number): 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 + *

    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()
    * - * sequence.mouseMove(element).mouseUp() + *

    Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 * - * 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 + * @param {(webdriver.WebElement|webdriver.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 + * Defaults to {@link webdriver.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 + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!ActionSequence} A self reference. + * @return {!webdriver.ActionSequence} A self reference. */ - mouseUp(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + mouseUp(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + mouseUp(opt_elementOrButton?: number): 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. + * @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 {!webdriver.ActionSequence} A self reference. */ - dragAndDrop(element: WebElement, location: WebElement|ILocation): ActionSequence; + dragAndDrop(element: WebElement, location: WebElement): ActionSequence; + dragAndDrop(element: WebElement, location: ILocation): ActionSequence; /** * Clicks a mouse button. * - * If an element is provided, the mouse will first be moved to the center + *

    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()
    * - * sequence.mouseMove(element).click() - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either + * @param {(webdriver.WebElement|webdriver.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 + * Defaults to {@link webdriver.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 + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!ActionSequence} A self reference. + * @return {!webdriver.ActionSequence} A self reference. */ - click(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + click(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + click(opt_elementOrButton?: number): ActionSequence; /** * Double-clicks a mouse button. * - * If an element is provided, the mouse will first be moved to the center of + *

    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()
    * - * sequence.mouseMove(element).doubleClick() + *

    Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 * - * 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 + * @param {(webdriver.WebElement|webdriver.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 + * Defaults to {@link webdriver.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 + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!ActionSequence} A self reference. + * @return {!webdriver.ActionSequence} A self reference. */ - doubleClick(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + doubleClick(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + doubleClick(opt_elementOrButton?: number): ActionSequence; /** * Performs a modifier key press. The modifier key is not released @@ -3317,7 +2366,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyDown(key: Key): ActionSequence; + keyDown(key: string): ActionSequence; /** * Performs a modifier key release. The release is targetted at the currently @@ -3327,7 +2376,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyUp(key: Key): ActionSequence; + keyUp(key: string): ActionSequence; /** * Simulates typing multiple keys. Each modifier key encountered in the @@ -3338,7 +2387,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - sendKeys(...var_args: Array): ActionSequence; + sendKeys(...var_args: any[]): ActionSequence; //endregion } @@ -3434,6 +2483,7 @@ declare namespace webdriver { */ scroll(offset: IOffset): TouchSequence; + /** * Scrolls the touch screen, starting on `elem` and moving by the specified * offset. @@ -3444,6 +2494,7 @@ declare namespace webdriver { */ scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; + /** * Flick, starting anywhere on the screen, at speed xspeed and yspeed. * @@ -3453,6 +2504,7 @@ declare namespace webdriver { */ flick(speed: ISpeed): TouchSequence; + /** * Flick starting at elem and moving by x and y at specified speed. * @@ -3464,29 +2516,26 @@ declare namespace webdriver { 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); + interface Alert { //region Methods @@ -3498,18 +2547,6 @@ declare namespace webdriver { */ 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 @@ -3543,27 +2580,47 @@ declare namespace webdriver { * 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.} + * @param {!webdriver.WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!webdriver.promise.Thenable.} alert A thenable + * that will be fulfilled with the promised alert. + * @constructor + * @extends {webdriver.Alert} + * @implements {webdriver.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); + interface AlertPromise extends Alert, webdriver.promise.IThenable { } - /** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ - class UnhandledAlertError extends webdriver.error.UnexpectedAlertOpenError { + /** + * An error returned to indicate that there is an unhandled modal dialog on the + * current page. + * @extends {bot.Error} + */ + interface UnhandledAlertError extends webdriver.error.Error { + //region Methods + + /** + * @return {string} The text displayed with the unhandled alert. + */ + getAlertText(): string; + + /** + * @return {!webdriver.Alert} The open alert. + * @deprecated Use {@link #getAlertText}. This method will be removed in + * 2.45.0. + */ + getAlert(): Alert; + + + //endregion } /** @@ -3573,9 +2630,7 @@ declare namespace webdriver { interface IBrowser { ANDROID: string; CHROME: string; - EDGE: string; FIREFOX: string; - IE: string; INTERNET_EXPLORER: string; IPAD: string; IPHONE: string; @@ -3596,45 +2651,6 @@ declare namespace webdriver { 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 @@ -3648,45 +2664,15 @@ declare namespace webdriver { //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 @@ -3719,12 +2705,6 @@ declare namespace webdriver { */ 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. @@ -3755,17 +2735,6 @@ declare namespace webdriver { */ 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. @@ -3784,16 +2753,6 @@ declare namespace webdriver { */ 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}. @@ -3801,37 +2760,17 @@ declare namespace webdriver { * 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; + setLoggingPrefs(prefs: webdriver.logging.Preferences): Builder; + setLoggingPrefs(prefs: { [key: string]: string }): 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. + * @param {!webdriver.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; + setProxy(config: ProxyConfig): Builder; /** * Sets how elements should be scrolled into view for interaction. @@ -3854,16 +2793,6 @@ declare namespace webdriver { */ 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. @@ -3871,149 +2800,12 @@ declare namespace webdriver { * capabilities for a new session. * @return {!Builder} A self reference. */ - withCapabilities(capabilities: Object|Capabilities): Builder; + withCapabilities(capabilities: Capabilities): Builder; + withCapabilities(capabilities: any): 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} @@ -4084,7 +2876,7 @@ declare namespace webdriver { SECURE_SSL: string; /** Whether the driver supports manipulating the app cache. */ - SUPPORTS_APPLICATION_CACHE: string; + SUPPORTS_APPLICATION_CACHE: string; /** Whether the driver supports locating elements with CSS selectors. */ SUPPORTS_CSS_SELECTORS: string; @@ -4118,7 +2910,8 @@ declare namespace webdriver { * capabilities to merge into this instance. * @constructor */ - constructor(opt_other?: Capabilities|Object); + constructor(opt_other?: Capabilities); + constructor(opt_other?: any); //endregion @@ -4134,7 +2927,8 @@ declare namespace webdriver { * merge into this instance. * @return {!webdriver.Capabilities} A self reference. */ - merge(other: Capabilities|Object): Capabilities; + merge(other: Capabilities): Capabilities; + merge(other: any): Capabilities; /** * @param {string} key The capability to set. @@ -4152,7 +2946,9 @@ declare namespace webdriver { * logging preferences. * @return {!webdriver.Capabilities} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Capabilities; + setLoggingPrefs(prefs: webdriver.logging.Preferences): Capabilities; + setLoggingPrefs(prefs: { [key: string]: string }): Capabilities; + /** * Sets the proxy configuration for this instance. @@ -4214,11 +3010,6 @@ declare namespace webdriver { */ 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. */ @@ -4392,8 +3183,6 @@ declare namespace webdriver { GET_AVAILABLE_LOG_TYPES: string; GET_LOG: string; GET_SESSION_LOGS: string; - - UPLOAD_FILE: string; } var CommandName: ICommandName; @@ -4452,47 +3241,19 @@ declare namespace webdriver { } /** - * Handles the execution of WebDriver {@link Command commands}. - * @interface + * Handles the execution of {@code webdriver.Command} objects. */ - 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); + interface CommandExecutor { + /** + * 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 + * {@link bot.response.ResponseObject} object. + * @param {!webdriver.Command} command The command to execute. + * @param {function(Error, !bot.response.ResponseObject=)} callback the function + * to invoke when the command response is ready. + */ + execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; } /** @@ -4522,42 +3283,39 @@ declare namespace webdriver { /** * 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. + * @return {!Array.<{fn: !Function, oneshot: boolean, + * scope: (Object|undefined)}>} The registered listeners for + * the given event type. */ - listeners(type: string): any; + listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: 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 + * @param {!Function} listenerFn 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. */ - addListener(type: string, fn: Function, opt_scope?:any, opt_oneshot?: boolean): EventEmitter; - + addListener(type: string, listenerFn: Function, opt_scope?:any): 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 {!Function} listenerFn 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; + once(type: string, listenerFn: 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 {!Function} listenerFn 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; + on(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; /** * Removes a previously registered event listener. @@ -4582,20 +3340,14 @@ declare namespace webdriver { /** * Interface for navigating back and forth in the browser history. */ - class Navigation { + interface WebDriverNavigation { //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() + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor */ - constructor(driver: WebDriver); + new (driver: WebDriver): WebDriverNavigation; //endregion @@ -4645,14 +3397,14 @@ declare namespace webdriver { /** * Provides methods for managing browser and driver state. */ - class Options { + interface WebDriverOptions { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: webdriver.WebDriver): WebDriverOptions; //endregion @@ -4665,13 +3417,13 @@ declare namespace webdriver { * @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. + * @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 {!webdriver.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; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; /** * Schedules a command to delete all cookies visible to the current page. @@ -4715,19 +3467,19 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Logs} The interface for managing driver * logs. */ - logs(): webdriver.Logs; + logs(): WebDriverLogs; /** * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver * timeouts. */ - timeouts(): webdriver.Timeouts; + timeouts(): WebDriverTimeouts; /** * @return {!webdriver.WebDriver.Window} The interface for managing the * current window. */ - window(): webdriver.Window; + window(): WebDriverWindow; //endregion } @@ -4735,14 +3487,14 @@ declare namespace webdriver { /** * An interface for managing timeout behavior for WebDriver instances. */ - class Timeouts { + interface WebDriverTimeouts { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverTimeouts; //endregion @@ -4797,7 +3549,7 @@ declare namespace webdriver { /** * An interface for managing the current window. */ - class Window { + interface WebDriverWindow { //region Constructors @@ -4805,7 +3557,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverWindow; //endregion @@ -4860,7 +3612,7 @@ declare namespace webdriver { /** * Interface for managing WebDriver log records. */ - class Logs { + interface WebDriverLogs { //region Constructors @@ -4868,7 +3620,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverLogs; //endregion @@ -4888,7 +3640,7 @@ declare namespace webdriver { * promise that will resolve to a list of log entries for the specified * type. */ - get(type: webdriver.logging.Type): webdriver.promise.Promise; + get(type: string): webdriver.promise.Promise; /** * Retrieves the log types available to this driver. @@ -4903,7 +3655,7 @@ declare namespace webdriver { /** * An interface for changing the focus of the driver to another frame or window. */ - class TargetLocator { + interface WebDriverTargetLocator { //region Constructors @@ -4911,7 +3663,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverTargetLocator; //endregion @@ -4935,47 +3687,44 @@ declare namespace webdriver { /** * 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 on the page. + *

    + * If the frame is specified by a number, the command will switch to the frame + * by its (zero-based) index into the {@code window.frames} collection. + *

    + * If the frame is specified by a string, the command will select the frame by + * its name or ID. To select sub-frames, simply separate the frame names/IDs by + * dots. As an example, "main.child" will select the frame with the name "main" + * and then its child "child". + *

    + * If the specified frame can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. + * @param {string|number} nameOrIndex The frame locator. + * @return {!webdriver.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; + frame(nameOrIndex: string): webdriver.promise.Promise; + frame(nameOrIndex: number): 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}. - * + * by its handle (as returned by {@code webdriver.WebDriver#getWindowHandles}). + *

    + * If the specificed window can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. * @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. + * @return {!webdriver.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. + * Schedules a command to change focus to the active alert dialog. This command + * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal + * dialog is not currently open. + * @return {!webdriver.Alert} The open alert. */ alert(): AlertPromise; @@ -5040,14 +3789,27 @@ declare namespace webdriver { //region Constructors /** - * @param {!(Session|promise.Promise)} session Either a + * @param {!(webdriver.Session|webdriver.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 + * @param {!webdriver.CommandExecutor} executor The executor to use when + * sending commands to the browser. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to * schedule commands through. Defaults to the active flow object. + * @constructor */ - constructor(session: Session|webdriver.promise.Promise, executor: Executor, opt_flow?: webdriver.promise.ControlFlow); + constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + + //endregion + + //region Static Properties + + static Navigation: WebDriverNavigation; + static Options: WebDriverOptions; + static Timeouts: WebDriverTimeouts; + static Window: WebDriverWindow; + static Logs: WebDriverLogs; + static TargetLocator: WebDriverTargetLocator; //endregion @@ -5055,29 +3817,29 @@ declare namespace webdriver { /** * Creates a new WebDriver client for an existing session. - * @param {!command.Executor} executor Command executor to use when querying - * for session details. + * @param {!webdriver.CommandExecutor} 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. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under. Defaults to the + * {@link webdriver.promise.controlFlow() currently active} control flow. + * @return {!webdriver.WebDriver} A new client for the specified session. */ - static attachToSession(executor: Executor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static attachToSession(executor: CommandExecutor, 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 + * @param {!webdriver.CommandExecutor} executor The executor to create the new + * session with. + * @param {!webdriver.Capabilities} desiredCapabilities The desired * capabilities for the new session. - * @param {promise.ControlFlow=} opt_flow The control flow all driver + * @param {webdriver.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} + * Defaults to the {@link webdriver.promise.controlFlow() currently active} * control flow. - * @return {!WebDriver} The driver for the newly created session. + * @return {!webdriver.WebDriver} The driver for the newly created session. */ - static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static createSession(executor: CommandExecutor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; //endregion @@ -5090,22 +3852,20 @@ declare namespace webdriver { 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. + * Schedules a {@code webdriver.Command} to be executed by this driver's + * {@code webdriver.CommandExecutor}. + * @param {!webdriver.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 + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the command result. */ schedule(command: Command, description: string): webdriver.promise.Promise; /** - * Sets the {@linkplain input.FileDetector file detector} that should be + * Sets the {@linkplain webdriver.FileDetector file detector} that should be * used with this instance. - * @param {input.FileDetector} detector The detector to use or {@code null}. + * @param {webdriver.FileDetector} detector The detector to use or {@code null}. */ setFileDetector(detector: FileDetector): void; @@ -5135,23 +3895,23 @@ declare namespace webdriver { /** * Creates a new action sequence using this driver. The sequence will not be - * scheduled for execution until {@link actions.ActionSequence#perform} is + * scheduled for execution until {@link webdriver.ActionSequence#perform} is * called. Example: - * - * driver.actions(). - * mouseDown(element1). - * mouseMove(element2). - * mouseUp(). - * perform(); - * - * @return {!actions.ActionSequence} A new action sequence for this instance. + *

    
    +         *   driver.actions().
    +         *       mouseDown(element1).
    +         *       mouseMove(element2).
    +         *       mouseUp().
    +         *       perform();
    +         * 
    + * @return {!webdriver.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 + * scheduled for execution until {@link webdriver.TouchSequence#perform} is * called. Example: * * driver.touchActions(). @@ -5159,7 +3919,7 @@ declare namespace webdriver { * doubleTap(element2). * perform(); * - * @return {!actions.TouchSequence} A new touch sequence for this instance. + * @return {!webdriver.TouchSequence} A new touch sequence for this instance. */ touchActions(): TouchSequence; @@ -5201,7 +3961,8 @@ declare namespace webdriver { * scripts return value. * @template T */ - executeScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute asynchronous JavaScript in the context of the @@ -5418,27 +4179,38 @@ declare namespace webdriver { * 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: + * 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 = driver.findElement(firstVisibleLink); * * function firstVisibleLink(driver) { * var links = driver.findElements(By.tagName('a')); - * return promise.filter(links, function(link) { - * return link.isDisplayed(); + * return webdriver.promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; * }); * } * - * @param {!(by.By|Function)} locator The locator to use. - * @return {!WebElementPromise} A WebElement that can be used to issue + * When running in the browser, a WebDriver cannot manipulate DOM elements + * directly; it may do so only through a {@link webdriver.WebElement} reference. + * This function may be used to generate a WebElement from a DOM element. A + * reference to the DOM element will be stored in a known location and this + * driver will attempt to retrieve it through {@link #executeScript}. If the + * element cannot be found (eg, it belongs to a different document than the + * one this instance is currently focused on), a + * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The + * locator to use. + * @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; + findElement(locatorOrElement: Locator|By.Hash|WebElement|Function): WebElementPromise; /** * Schedules a command to test if an element is present on the page. @@ -5447,36 +4219,35 @@ declare namespace webdriver { * 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 + * @param {!(webdriver.Locator|webdriver.By.Hash|Element| + * Function)} locatorOrElement The locator to use, or the actual + * DOM element to be located by the server. + * @return {!webdriver.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; + isElementPresent(locatorOrElement: Locator|By.Hash|WebElement|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 + * @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 resolve to an array of WebElements. */ - findElements(locator: By|Function): webdriver.promise.Promise; + findElements(locator: Locator|By.Hash|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 screenshot of the entire display containing the browser + *
    * - * 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 + * @return {!webdriver.promise.Promise.} A promise that will be * resolved to the screenshot as a base-64 encoded PNG. */ takeScreenshot(): webdriver.promise.Promise; @@ -5485,25 +4256,45 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Options} The options interface for this * instance. */ - manage(): webdriver.Options; + manage(): WebDriverOptions; /** * @return {!webdriver.WebDriver.Navigation} The navigation interface for this * instance. */ - navigate(): Navigation; + navigate(): WebDriverNavigation; /** * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for * this instance. */ - switchTo(): webdriver.TargetLocator; + switchTo(): WebDriverTargetLocator; //endregion } interface IWebElementId { - [ELEMENT:string]: string; + ELEMENT: string; + } + + /** + * 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; } /** @@ -5763,7 +4554,7 @@ declare namespace webdriver { * 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; + findElement(locator: Locator|By.Hash|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this @@ -5774,7 +4565,7 @@ declare namespace webdriver { * @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; + isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that @@ -5785,9 +4576,10 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: By|Function): webdriver.promise.Promise; + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; } + /** * Defines an object that can be asynchronously serialized to its WebDriver * wire representation. @@ -5808,6 +4600,7 @@ declare namespace webdriver { 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 @@ -5833,59 +4626,35 @@ declare namespace webdriver { */ 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. + * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!(webdriver.promise.Promise.| + * webdriver.WebElement.Id)} id The server-assigned opaque ID for the + * underlying DOM element. + * @constructor */ - constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise|string); + constructor(driver: WebDriver, id: webdriver.promise.Promise|IWebElementId); /** - * @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. + * Wire protocol definition of a WebElement ID. + * @typedef {{ELEMENT: string}} + * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol */ - static buildId(id: string, opt_noLegacy?: boolean): Object; + static Id: IWebElementId; /** - * 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. + * The property key used in the wire protocol to indicate that a JSON object + * contains the ID of a WebElement. + * @type {string} + * @const */ - static extractId(obj: IWebElementId): string; + static ELEMENT_KEY: 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; + getDriver(): WebDriver; /** * Schedule a command to find a descendant of this element. If the element @@ -5919,40 +4688,35 @@ declare namespace webdriver { * }); * } * - * @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 + * @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; + findElement(locator: Locator|By.Hash|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 + * @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. - * @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; + isElementPresent(locator: Locator|By.Hash|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 + * @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; + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedules a command to click on this element. @@ -5963,7 +4727,7 @@ declare namespace webdriver { /** * Schedules a command to type a sequence on the DOM element represented by this - * promsieinstance. + * 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 @@ -6035,7 +4799,7 @@ declare namespace webdriver { * * @param {string} cssStyleProperty The name of the CSS style property to look * up. - * @return {!promise.Promise} A promise that will be + * @return {!webdriver.promise.Promise.} A promise that will be * resolved with the requested CSS value. */ getCssValue(cssStyleProperty: string): webdriver.promise.Promise; @@ -6121,10 +4885,10 @@ declare namespace webdriver { 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 + * 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 {!promise.Promise} A promise that will be resolved + * @return {!webdriver.promise.Promise.} A promise that will be resolved * when the element has been cleared. */ clear(): webdriver.promise.Promise; @@ -6136,18 +4900,6 @@ declare namespace webdriver { */ 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 @@ -6155,6 +4907,25 @@ declare namespace webdriver { */ 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; + + /** + * Returns the raw ID string ID for this element. + * @return {!webdriver.promise.Promise} A promise that resolves to this + * element's raw ID as a string value. + * @package + */ + getRawId(): webdriver.promise.Promise; + + /** @override */ + serialize(): 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 @@ -6162,8 +4933,14 @@ declare namespace webdriver { */ getInnerHtml(): webdriver.promise.Promise; - /** @override */ - serialize(): webdriver.promise.Promise; + /** + * Compares to WebElements for equality. + * @param {!webdriver.WebElement} a A WebElement. + * @param {!webdriver.WebElement} b A WebElement. + * @return {!webdriver.promise.Promise} A promise that will be resolved to + * whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; } /** @@ -6189,14 +4966,6 @@ declare namespace webdriver { * @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. @@ -6306,31 +5075,191 @@ declare namespace webdriver { * @template R */ thenFinally(callback: () => any): webdriver.promise.Promise; + } + + namespace By { + /** + * Locates elements that have a specific class name. The returned locator + * is equivalent to searching for elements with the CSS selector ".clazz". + * + * @param {string} className The class name to search for. + * @return {!webdriver.Locator} 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 + */ + function className(value: string): Locator; /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: + * Locates elements using a CSS selector. For browsers that do not support + * CSS selectors, WebDriver implementations may return an + * {@linkplain bot.Error.State.INVALID_SELECTOR invalid selector} error. An + * implementation may, however, emulate the CSS selector 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 + * @param {string} selector The CSS selector to use. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html */ - catch(errback: Function): webdriver.promise.Promise; + function css(value: string): Locator; + + /** + * Locates an element by its ID. + * + * @param {string} id The ID to search for. + * @return {!webdriver.Locator} The new locator. + */ + function id(value: string): Locator; + + /** + * Locates link elements whose {@linkplain webdriver.WebElement#getText visible + * text} matches the given string. + * + * @param {string} text The link text to search for. + * @return {!webdriver.Locator} The new locator. + */ + function linkText(value: string): Locator; + + /** + * 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): !webdriver.promise.Promise} A new, + * JavaScript-based locator function. + */ + function js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates elements whose {@code name} attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!webdriver.Locator} The new locator. + */ + function name(value: string): Locator; + + /** + * 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 {!webdriver.Locator} The new locator. + */ + function partialLinkText(value: string): Locator; + + /** + * Locates elements with a given tag name. The returned locator is + * equivalent to using the + * [getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) + * DOM function. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html + */ + function tagName(value: string): Locator; + + /** + * 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 {@code "//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 {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ + function xpath(value: string): Locator; + + /** + * 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 Hash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + } + + /** + * An element locator. + */ + class Locator { + /** + * An element locator. + * @param {string} using The type of strategy to use for this locator. + * @param {string} value The search target of this locator. + * @constructor + */ + constructor(using: string, value: string); + + + /** + * Maps {@link webdriver.By.Hash} keys to the appropriate factory function. + * @type {!Object.} + * @const + */ + static Strategy: { + className: typeof webdriver.By.className; + css: typeof webdriver.By.css; + id: typeof webdriver.By.id; + js: typeof webdriver.By.js; + linkText: typeof webdriver.By.linkText; + name: typeof webdriver.By.name; + partialLinkText: typeof webdriver.By.partialLinkText; + tagName: typeof webdriver.By.tagName; + xpath: typeof webdriver.By.xpath; + }; + + /** + * Verifies that a {@code value} is a valid locator to use for searching for + * elements on the page. + * + * @param {*} value The value to check is a valid locator. + * @return {!(webdriver.Locator|Function)} A valid locator object or function. + * @throws {TypeError} If the given value is an invalid locator. + */ + static checkLocator(value: any): Locator | Function; + + /** + * The search strategy to use when searching for an element. + * @type {string} + */ + using: string; + + /** + * The search target for this locator. + * @type {string} + */ + value: string; + + /** @return {string} String representation of this locator. */ + toString(): string; } /** @@ -6346,7 +5275,8 @@ declare namespace webdriver { * capabilities. * @constructor */ - constructor(id: string, capabilities: Capabilities|Object); + constructor(id: string, capabilities: Capabilities); + constructor(id: string, capabilities: any); //endregion @@ -6360,7 +5290,7 @@ declare namespace webdriver { /** * @return {!webdriver.Capabilities} This session's capabilities. */ - getCapabilities(): webdriver.Capabilities; + getCapabilities(): Capabilities; /** * Retrieves the value of a specific capability. @@ -6446,6 +5376,10 @@ declare module 'selenium-webdriver/chrome' { export = chrome; } +declare module 'selenium-webdriver/firefox' { + export = firefox; +} + declare module 'selenium-webdriver/executors' { export = executors; } From 08850929a37774c447dba246e80a2e65d5035d33 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 17:10:58 +0800 Subject: [PATCH 499/844] Since express has been imported, it should be used --- twilio/twilio.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 { From a715a568847661320c4f643dc1c6f318c0a3e440 Mon Sep 17 00:00:00 2001 From: Jonny Stoten Date: Thu, 15 Sep 2016 14:19:23 +0100 Subject: [PATCH 500/844] Add some typings for multipart upload (#11223) --- aws-sdk/aws-sdk.d.ts | 5 +++++ 1 file changed, 5 insertions(+) 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 { From 1a97636e037e5a0c1dff8d723c8585db24ccf433 Mon Sep 17 00:00:00 2001 From: paulmorphy Date: Thu, 15 Sep 2016 15:20:21 +0200 Subject: [PATCH 501/844] Added definition for the missing dns.setServers(servers) method (#11183) * Added definition for the missing dns.setServers(servers) method Method is documented here: https://nodejs.org/docs/latest/api/dns.html#dns_dns_setservers_servers * Updated definition for dns.resolveMx The addresses argument passed to the callback function will contain an array of objects containing both a priority and exchange property: https://nodejs.org/docs/latest/api/dns.html#dns_dns_resolvemx_hostname_callback --- node/node.d.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/node/node.d.ts b/node/node.d.ts index 2094959e6e..e4e66e69ee 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1396,18 +1396,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; From 6a9eb69291eb1154cce41664c668ab479c6c5732 Mon Sep 17 00:00:00 2001 From: Kazuki Oota Date: Thu, 15 Sep 2016 22:22:12 +0900 Subject: [PATCH 502/844] add access property to table. (#11158) * add access property. * fix ci error. --- azure-mobile-apps/azure-mobile-apps-tests.ts | 7 +++++++ azure-mobile-apps/azure-mobile-apps.d.ts | 4 ++++ 2 files changed, 11 insertions(+) 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; From d51cb64351dad6f50a890d8cd2ddb2c2a90e3104 Mon Sep 17 00:00:00 2001 From: Jacob Baskin Date: Thu, 15 Sep 2016 09:24:40 -0400 Subject: [PATCH 503/844] Typings for Busboy (#11227) * Add typings for Busboy. * Fix indent style * Fix for es6 imports * Re-add module def --- busboy/busboy-tests.ts | 39 +++++++++++++++++++++++++++ busboy/busboy.d.ts | 60 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 busboy/busboy-tests.ts create mode 100644 busboy/busboy.d.ts 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; +} From 1e4db4e1877c0a224f8fd4a6a9bd143a205ed3ea Mon Sep 17 00:00:00 2001 From: Mykhailo Stadnyk Date: Thu, 15 Sep 2016 16:40:19 +0300 Subject: [PATCH 504/844] Added type definitions for new module canvas-gauges (#11211) * Added type definitions for new module canvas-gauges * definitions re-factored as a ghost module * Typo fixed in url protocol --- canvas-gauges/canvas-gauges-tests.ts | 20 ++ canvas-gauges/canvas-gauges.d.ts | 263 +++++++++++++++++++++++++++ 2 files changed, 283 insertions(+) create mode 100644 canvas-gauges/canvas-gauges-tests.ts create mode 100644 canvas-gauges/canvas-gauges.d.ts 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; +} From 9d66141d077d4f17f148b41fa1adca7a651102e4 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:41:55 +0800 Subject: [PATCH 505/844] [node.d.ts] Update cluster definition (#11235) * Update cluster * Add ; --- node/node.d.ts | 171 +++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 152 insertions(+), 19 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index e4e66e69ee..346f7e7413 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -741,17 +741,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 { @@ -766,33 +779,153 @@ declare module "cluster" { isDead(): boolean; } - export var settings: ClusterSettings; + export interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: Function): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSetupMasterSettings): void; + worker: Worker; + workers: { + [index: string]: Worker + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: any) => void): this; + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: any) => void): this; + + once(event: string, listener: Function): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: any) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: any) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: any) => void): this; + + } + + export function disconnect(callback ?: Function): void; + export function fork(env?: any): Worker; export var isMaster: boolean; export var isWorker: boolean; - export function setupMaster(settings?: ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; + // TODO: cluster.schedulingPolicy + export var settings: ClusterSettings; + export function setupMaster(settings?: ClusterSetupMasterSettings): void; export var worker: Worker; export var workers: { [index: string]: Worker }; - // Event emitter - export function addListener(event: string, listener: Function): void; - export function on(event: "disconnect", listener: (worker: Worker) => void): void; - export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void; - export function on(event: "fork", listener: (worker: Worker) => void): void; - export function on(event: "listening", listener: (worker: Worker, address: any) => void): void; - export function on(event: "message", listener: (worker: Worker, message: any) => void): void; - export function on(event: "online", listener: (worker: Worker) => void): void; - export function on(event: "setup", listener: (settings: any) => void): void; - export function on(event: string, listener: Function): any; - export function once(event: string, listener: Function): void; - export function removeListener(event: string, listener: Function): void; - export function removeAllListeners(event?: string): void; - export function setMaxListeners(n: number): void; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + export function addListener(event: string, listener: Function): Cluster; + export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function on(event: string, listener: Function): Cluster; + export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function on(event: "fork", listener: (worker: Worker) => void): Cluster; + export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function on(event: "online", listener: (worker: Worker) => void): Cluster; + export function on(event: "setup", listener: (settings: any) => void): Cluster; + + export function once(event: string, listener: Function): Cluster; + export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function once(event: "fork", listener: (worker: Worker) => void): Cluster; + export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function once(event: "online", listener: (worker: Worker) => void): Cluster; + export function once(event: "setup", listener: (settings: any) => void): Cluster; + + export function removeListener(event: string, listener: Function): Cluster; + export function removeAllListeners(event?: string): Cluster; + export function setMaxListeners(n: number): Cluster; + export function getMaxListeners(): number; export function listeners(event: string): Function[]; export function emit(event: string, ...args: any[]): boolean; + export function listenerCount(type: string): number; + + export function prependListener(event: string, listener: Function): Cluster; + export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function prependOnceListener(event: string, listener: Function): Cluster; + export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function eventNames(): string[]; } declare module "zlib" { From a72353df2416348b0d3f176b8019229c87c064bf Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:42:17 +0800 Subject: [PATCH 506/844] [node-tests.ts] A test should move to events_tests in node (#11237) * A test should move to events_tests in node v6.x * A test should move to events_tests in node v4.x --- node/node-4-tests.ts | 18 ++++++++++-------- node/node-tests.ts | 18 ++++++++++-------- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 35fe3553a6..1aebd6d201 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -108,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"); + } + } + } } //////////////////////////////////////////////////// @@ -167,14 +177,6 @@ namespace fs_tests { } -class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); - } -} - /////////////////////////////////////////////////////// /// Buffer tests : https://nodejs.org/api/buffer.html /////////////////////////////////////////////////////// diff --git a/node/node-tests.ts b/node/node-tests.ts index 7e010bc9a3..19048bea9c 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -118,6 +118,16 @@ namespace events_tests { result = emitter.eventNames(); } + + { + class Networker extends events.EventEmitter { + constructor() { + super(); + + this.emit("mingling"); + } + } + } } //////////////////////////////////////////////////// @@ -212,14 +222,6 @@ namespace fs_tests { } } -class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); - } -} - /////////////////////////////////////////////////////// /// Buffer tests : https://nodejs.org/api/buffer.html /////////////////////////////////////////////////////// From d6854025495626c9e92efd666032f98313a487ce Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:42:34 +0800 Subject: [PATCH 507/844] [node-tests.ts] The test should test type, not function (#11238) * The test should test type, not function * The test should test type, not function --- node/node-4-tests.ts | 8 ++++---- node/node-tests.ts | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 1aebd6d201..30098021ec 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -906,14 +906,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); } } @@ -922,8 +921,9 @@ namespace process_tests{ /////////////////////////////////////////////////////////// import * as c from "console"; -namespace console_tests{ +namespace console_tests { { - assert(c === console); + var _c: Console = console; + _c = c; } } diff --git a/node/node-tests.ts b/node/node-tests.ts index 19048bea9c..9a2c2e22cd 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -1112,14 +1112,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); } } @@ -1128,9 +1127,10 @@ namespace process_tests{ /////////////////////////////////////////////////////////// import * as c from "console"; -namespace console_tests{ +namespace console_tests { { - assert(c === console); + var _c: Console = console; + _c = c; } } From 89030200ceb205da4db2fc56d8e750e9c16be92f Mon Sep 17 00:00:00 2001 From: Jeremy Foster Date: Thu, 15 Sep 2016 06:42:49 -0700 Subject: [PATCH 508/844] add err:any to close, flush, and drain methods (#11239) --- serialport/serialport.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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: { From 62f98f1a3bce86763366541830b482e4117b5cfb Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:43:21 +0800 Subject: [PATCH 509/844] [node-tests.ts] Clean up http_tests and net_tests (#11240) * Clean up http_tests and net_tests * Clean up fs tests and wrap in namespace --- node/node-4-tests.ts | 69 +++++++++++++++++++++++++------------------- node/node-tests.ts | 69 +++++++++++++++++++++++++------------------- 2 files changed, 80 insertions(+), 58 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 30098021ec..2d84e8f175 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -379,27 +379,18 @@ var tlsOpts: tls.TlsOptions = { }; var tlsSocket = tls.connect(tlsOpts); - +//////////////////////////////////////////////////// +/// Http tests : http://nodejs.org/api/http.html /// //////////////////////////////////////////////////// -// Make sure .listen() and .close() retuern a Server instance -http.createServer().listen(0).close().address(); -net.createServer().listen(0).close().address(); - -var request = http.request('http://0.0.0.0'); -request.once('error', function () {}); -request.setNoDelay(true); -request.abort(); - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html -//////////////////////////////////////////////////// namespace http_tests { - // Status codes - var code = 100; - var codeMessage = http.STATUS_CODES['400']; - var codeMessage = http.STATUS_CODES[400]; + { + // Status codes + var codeMessage = http.STATUS_CODES['400']; + var codeMessage = http.STATUS_CODES[400]; + } + { var agent: http.Agent = new http.Agent({ keepAlive: true, keepAliveMsecs: 10000, @@ -409,20 +400,29 @@ namespace http_tests { var agent: http.Agent = http.globalAgent; - http.request({ - agent: false - }); - http.request({ - agent: agent - }); - http.request({ - agent: undefined - }); + http.request({agent: false}); + http.request({agent: agent}); + http.request({agent: undefined}); + } + + { + // Make sure .listen() and .close() retuern a Server instance + http.createServer().listen(0).close().address(); + net.createServer().listen(0).close().address(); + } + + { + var request = http.request('http://0.0.0.0'); + request.once('error', function() { }); + request.setNoDelay(true); + request.abort(); + } } -//////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + namespace https_tests { var agent: https.Agent = new https.Agent({ keepAlive: true, @@ -927,3 +927,14 @@ namespace console_tests { _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-tests.ts b/node/node-tests.ts index 9a2c2e22cd..ef9f48783f 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -554,27 +554,18 @@ var connOpts: tls.ConnectionOptions = { }; var tlsSocket = tls.connect(connOpts); - +//////////////////////////////////////////////////// +/// Http tests : http://nodejs.org/api/http.html /// //////////////////////////////////////////////////// -// Make sure .listen() and .close() retuern a Server instance -http.createServer().listen(0).close().address(); -net.createServer().listen(0).close().address(); - -var request = http.request('http://0.0.0.0'); -request.once('error', function () {}); -request.setNoDelay(true); -request.abort(); - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html -//////////////////////////////////////////////////// namespace http_tests { - // Status codes - var code = 100; - var codeMessage = http.STATUS_CODES['400']; - var codeMessage = http.STATUS_CODES[400]; + { + // Status codes + var codeMessage = http.STATUS_CODES['400']; + var codeMessage = http.STATUS_CODES[400]; + } + { var agent: http.Agent = new http.Agent({ keepAlive: true, keepAliveMsecs: 10000, @@ -584,20 +575,29 @@ namespace http_tests { var agent: http.Agent = http.globalAgent; - http.request({ - agent: false - }); - http.request({ - agent: agent - }); - http.request({ - agent: undefined - }); + http.request({agent: false}); + http.request({agent: agent}); + http.request({agent: undefined}); + } + + { + // Make sure .listen() and .close() retuern a Server instance + http.createServer().listen(0).close().address(); + net.createServer().listen(0).close().address(); + } + + { + var request = http.request('http://0.0.0.0'); + request.once('error', function() { }); + request.setNoDelay(true); + request.abort(); + } } -//////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + namespace https_tests { var agent: https.Agent = new https.Agent({ keepAlive: true, @@ -1134,6 +1134,17 @@ namespace console_tests { } } +/////////////////////////////////////////////////// +/// Net Tests : https://nodejs.org/api/net.html /// +/////////////////////////////////////////////////// + +namespace net_tests { + { + // Make sure .listen() and .close() retuern a Server instance + net.createServer().listen(0).close().address(); + } +} + /***************************************************************************** * * * The following tests are the modules not mentioned in document but existed * From 48f9040fcc94f007cc7f14415ee4959988543949 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:44:31 +0800 Subject: [PATCH 510/844] [node-tests.ts] Clean up crypto_tests and wrap in namespace (#11242) * Clean up crypto_tests tests and wrap in namespace * Clean up crypto_tests and wrap in namespace * Use let to declares a block scope local variable * Use let to declares a block scope local variable --- node/node-4-tests.ts | 80 ++++++++++++++++++++++++-------------------- node/node-tests.ts | 80 ++++++++++++++++++++++++-------------------- 2 files changed, 86 insertions(+), 74 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 2d84e8f175..2de910db67 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -316,51 +316,57 @@ function stream_readable_pipe_test() { r.close(); } -//////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html -//////////////////////////////////////////////////// +//////////////////////////////////////////////////////// +/// Crypto tests : http://nodejs.org/api/crypto.html /// +//////////////////////////////////////////////////////// -var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); +namespace crypto_tests { + { + var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); + } + + { + let hmac: crypto.Hmac; + (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { + let hash: Buffer | string = hmac.read(); + }); + } + + { + //crypto_cipher_decipher_string_test + let key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: string = "This is the clear text."; + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherText: string = cipher.update(clearText, "utf8", "hex"); + cipherText += cipher.final("hex"); -{ - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - let hash: Buffer|string = hmac.read(); - }); -} + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let clearText2: string = decipher.update(cipherText, "hex", "utf8"); + clearText2 += decipher.final("utf8"); -function crypto_cipher_decipher_string_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:string = "This is the clear text."; - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherText:string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); + assert.equal(clearText2, clearText); + } - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var clearText2:string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); + { + //crypto_cipher_decipher_buffer_test + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherBuffers: Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); - assert.equal(clearText2, clearText); -} + let cipherText: Buffer = Buffer.concat(cipherBuffers); -function crypto_cipher_decipher_buffer_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherBuffers:Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let decipherBuffers: Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); - var cipherText:Buffer = Buffer.concat(cipherBuffers); + let clearText2: Buffer = Buffer.concat(decipherBuffers); - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var decipherBuffers:Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - var clearText2:Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); + assert.deepEqual(clearText2, clearText); + } } //////////////////////////////////////////////////// diff --git a/node/node-tests.ts b/node/node-tests.ts index ef9f48783f..e0600d936d 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -491,51 +491,57 @@ function simplified_stream_ctor_test() { }) } -//////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html -//////////////////////////////////////////////////// +//////////////////////////////////////////////////////// +/// Crypto tests : http://nodejs.org/api/crypto.html /// +//////////////////////////////////////////////////////// -var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); +namespace crypto_tests { + { + var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); + } + + { + let hmac: crypto.Hmac; + (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { + let hash: Buffer | string = hmac.read(); + }); + } + + { + //crypto_cipher_decipher_string_test + let key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: string = "This is the clear text."; + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherText: string = cipher.update(clearText, "utf8", "hex"); + cipherText += cipher.final("hex"); -{ - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - let hash: Buffer|string = hmac.read(); - }); -} + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let clearText2: string = decipher.update(cipherText, "hex", "utf8"); + clearText2 += decipher.final("utf8"); -function crypto_cipher_decipher_string_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:string = "This is the clear text."; - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherText:string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); + assert.equal(clearText2, clearText); + } - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var clearText2:string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); + { + //crypto_cipher_decipher_buffer_test + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherBuffers: Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); - assert.equal(clearText2, clearText); -} + let cipherText: Buffer = Buffer.concat(cipherBuffers); -function crypto_cipher_decipher_buffer_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherBuffers:Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let decipherBuffers: Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); - var cipherText:Buffer = Buffer.concat(cipherBuffers); + let clearText2: Buffer = Buffer.concat(decipherBuffers); - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var decipherBuffers:Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - var clearText2:Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); + assert.deepEqual(clearText2, clearText); + } } //////////////////////////////////////////////////// From 4871fb2876696025b0a1704d629378915d7cdd3c Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:45:12 +0800 Subject: [PATCH 511/844] Add listening for http.Server (#11246) --- node/node.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node/node.d.ts b/node/node.d.ts index 346f7e7413..81b13e4e1d 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -592,6 +592,7 @@ declare module "http" { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; timeout: number; + listening: boolean; } /** * @deprecated Use IncomingMessage From 9dbdb50546cbec870208edb11e962872128cc1f8 Mon Sep 17 00:00:00 2001 From: Blake Smith Date: Thu, 15 Sep 2016 08:46:59 -0500 Subject: [PATCH 512/844] Updating elasticsearch definition with some of the missing components (#11149) * Updating elasticsearch definition with some of the missing components. (https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-cluster-getsettings) Adding Cluster definitions, one Cat definition. * Correcting header. --- CONTRIBUTORS.md | 1 + elasticsearch/elasticsearch-tests.ts | 40 +++++++++++++ elasticsearch/elasticsearch.d.ts | 90 +++++++++++++++++++++++++++- 3 files changed, 130 insertions(+), 1 deletion(-) 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/elasticsearch/elasticsearch-tests.ts b/elasticsearch/elasticsearch-tests.ts index 14070aa8cc..6d308dc6ed 100644 --- a/elasticsearch/elasticsearch-tests.ts +++ b/elasticsearch/elasticsearch-tests.ts @@ -45,4 +45,44 @@ client.create({ index: 'index', type: 'type' }, (err, repsonse, status) => { +}); + +client.cluster.getSettings({ + masterTimeout: 100 +}, (err, response) => { +}); + +client.cluster.health({ + masterTimeout: 100 +}, (err, response) => { +}); + +client.cluster.pendingTasks({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.putSettings({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.putSettings({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.reroute({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.state({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.stats({ + ignore: 1 +}, (err, response) => { }); \ No newline at end of file diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index ec67e6a59d..e2079b19d0 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -1,12 +1,14 @@ // Type definitions for elasticsearch // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt +// Definitions by: Casper Skydt , Blake Smith // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module Elasticsearch { export class Client { constructor(params: ConfigOptions); indices: Indices; + cluster: Cluster; + cat: Cat; bulk(params: BulkIndexDocumentsParams): PromiseLike; bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; create(params: CreateDocumentParams): PromiseLike; @@ -230,6 +232,7 @@ declare module Elasticsearch { scroll?: string; search_type?: string; fields?: string[]; + from?: number; size?: number; sort?: string | string[] | boolean; _source?: string | string[] | boolean; @@ -333,6 +336,91 @@ declare module Elasticsearch { body: string | any; index: string | string[] | boolean; } + + export interface Cat { + health(params: CatHealthOptions, callback: (error: any, response: any) => void): void; + health(params: CatHealthOptions): PromiseLike + } + + export interface CatHealthOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + h?: string | string[] | boolean; + help?: boolean; + ts?: boolean; + v?: boolean; + } + + export interface Cluster { + getSettings(params: ClusterGetSettingsOptions, callback: (error: any, response: any) => void): void; + getSettings(params: ClusterGetSettingsOptions): PromiseLike; + health(params: ClusterHealthOptions, callback: (error: any, response: any) => void): void; + health(params: ClusterHealthOptions): PromiseLike; + pendingTasks(params: ClusterPendingTasksOptions, callback: (error: any, response: any) => void): void; + pendingTasks(params: ClusterPendingTasksOptions): PromiseLike; + putSettings(params: ClusterPutSettingsOptions, callback: (error: any, response: any) => void): void; + putSettings(params: ClusterPutSettingsOptions): PromiseLike; + reroute(params: ClusterRerouteOptions, callback: (error: any, response: any) => void): void; + reroute(params: ClusterRerouteOptions): PromiseLike; + state(params: ClusterStateOptions, callback: (error: any, response: any) => void): void; + state(params: ClusterStateOptions): PromiseLike; + stats(params: ClusterStatsOptions, callback: (error: any, response: any) => void): void; + stats(params: ClusterStatsOptions): PromiseLike; + } + + export interface ClusterGetSettingsOptions extends GenericParams { + flatSettings?: boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterHealthOptions extends GenericParams { + level?: string; // cluster, indices, shards + local?: boolean; + masterTimeout?: number | Date; + waitForActiveShards?: number; + waitForNodes?: string; + waitForRelocatingShards?: number; + waitForStatus?: string; // green, yellow, red + index?: string | string[] | boolean; + } + + export interface ClusterPendingTasksOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + } + + export interface ClusterPutSettingsOptions extends GenericParams { + flatSettings?: boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterRerouteOptions extends GenericParams { + dryRun?: boolean; + explain?: boolean; + metric?: string | string[] | boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterStateOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + flatSettings?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: string; // open, closed, none, all (default open) + index?: string | string[] | boolean; + metric?: string | string[] | boolean; + } + + export interface ClusterStatsOptions extends GenericParams { + flatSettings?: boolean; + human?: boolean; + timeout?: number | Date; + nodeId?: string | string[] | boolean; + } } declare module "elasticsearch" { From 22a0c3a9a6e798052192b49c104c67057288df6d Mon Sep 17 00:00:00 2001 From: NoHomey Date: Thu, 15 Sep 2016 18:22:20 +0300 Subject: [PATCH 513/844] [jest] updating definition to match latest API reference --- jest/jest-tests.ts | 232 ++++++++++++++++++++++++++++++++++++++++++++- jest/jest.d.ts | 158 ++++++++++++------------------ 2 files changed, 290 insertions(+), 100 deletions(-) diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index f3e33c4061..04fba5ab09 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -37,8 +37,6 @@ describe('fetchCurrentUser', function() { // unmock is the recommended approach for unmocking... jest.unmock('../displayUser.js') -// ...but dontMock also still works. -jest.dontMock('jquery'); describe('displayUser', function() { it('displays a user after a click', function() { @@ -100,6 +98,157 @@ describe('CheckboxWithLabel', function() { }); }); +jest.runAllTicks(); +xdescribe('Hooks and Suits', function () { + let tested: boolean; + + beforeEach(function () { + tested = false; + }); + + afterEach(function () { + tested = true; + }); + + test('tested', function () { + expect(tested).toBeTruthy(); + expect(tested).not.toBeFalsy(); + }); + + fit('tested', function () { + expect(tested).toBeDefined(); + expect(tested).not.toBeUndefined(); + }); + + xit('expect null to be null', function () { + expect(null).toBeNull(); + }); +}); + +describe('compartion', function () { + var sum: (a: number, b: number) => number = require.requireMock('../sum'); + + it('compares is 7 + 2 greater than 3', function () { + expect(sum(7, 2)).toBeGreaterThan(3); + }); + + it('compares is 2 + 7 greater than or equal to 3', function () { + expect(sum(2, 7)).toBeGreaterThanOrEqual(3); + }); + + it('compares is 3 less than 3 + 4', function () { + expect(3).toBeLessThan(sum(3, 4)); + }); + + it('compares is 3 less than or equal to 4 + 3', function () { + expect(3).toBeLessThanOrEqual(sum(4, 3)); + }); + + it('works sanely with simple decimals', function () { + expect(0.2 + 0.1).toBeCloseTo(0.3, 5); + }); +}); + +describe('toThrow API', function () { + function throwTypeError(): void { + throw new TypeError('toThrow Definition was out of date'); + } + + it('throws', function () { + expect(throwTypeError()).toThrow(); + }); + + it('throws TypeError', function () { + expect(throwTypeError()).toThrowError(TypeError); + }); + + it('throws \'Definition was out of date\'', function () { + expect(throwTypeError()).toThrowError(/Definition was out of date/); + }); + + it('throws \'toThorow Definition was out of date\'', function () { + expect(throwTypeError()).toThrowError('toThrow Definition was out of date'); + }); +}); + +describe('missing tests', function () { + it('creates closures', function () { + class Closure { + private arg: T; + + public constructor(private fn: (arg: T) => void) { + this.fn = fn; + } + + public bind(arg: T): void { + this.arg = arg; + } + + public call(): void { + this.fn(this.arg); + } + } + + type StringClosure = (arg: string) => void; + let spy: jest.Mock = jest.fn(); + let closure: Closure = new Closure(spy); + closure.bind('jest'); + closure.call(); + expect(spy).lastCalledWith('jest'); + expect(spy).toBeCalledWith('jest'); + expect(jest.isMockFunction(spy)).toBeTruthy(); + }); + + it('tests all mising Mocks functionality', function () { + type FruitsGetter = () => Array; + let mock: jest.Mock = jest.fn(); + mock.mockImplementationOnce(() => ['Orange', 'Apple', 'Plum']) + jest.setMock('./../tesks/getFruits', mock); + const getFruits: FruitsGetter = require('./../tesks/getFruits'); + expect(getFruits()).toContain('Orange'); + mock.mockReturnValueOnce(['Apple', 'Plum']); + expect(mock()).not.toContain('Orange'); + mock.mockReturnValue([]); //Deprecated: Use jest.fn(() => value) instead. + mock.mockClear(); + let thisMock: jest.Mock = jest.fn().mockReturnThis(); + expect(thisMock()).toBe(this); + }); + + it('creates snapshoter', function () { + jest.disableAutomock(); + jest.mock('./render', () => jest.fn((): string => "{Link to: \"facebook\"}"), { virtual: true }); + const render: () => string = require('./render'); + expect(render()).toMatch(/Link/); + jest.enableAutomock(); + }); + + it('runs only pending timers', function () { + jest.useRealTimers(); + setTimeout(() => expect(1).not.toEqual(0), 3000); + jest.runOnlyPendingTimers(); + }); + + it('runs all timers', function () { + jest.clearAllTimers(); + jest.useFakeTimers(); + setTimeout(() => expect(0).not.toEqual(1), 3000); + jest.runAllTimers(); + }); + + it('cleares cache', function () { + const sum1 = require('../sum'); + jest.resetModules(); + const sum2 = require('../sum'); + expect(sum1).not.toBe(sum2); + }) +}); + +describe('toMatchSnapshot', function () { + it('compares snapshots', function () { + expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot(); + }); +}); + function testInstances() { var mockFn = jest.fn(); var a = new mockFn(); @@ -123,3 +272,82 @@ function testMockImplementation() { mockFn.mock.calls[0][0] === 0; // true mockFn.mock.calls[1][0] === 1; // true } + +// Test from jest Docs: +describe('genMockFromModule', function () { + // Interfaces: + interface MockFiles { + [index: string]: string; + } + + interface MockedFS { + readdirSync: (dir: string) => string[]; + __setMockFiles: (newMockFiles: MockFiles) => void ; + } + + // ------------------------------------------------------------------------------------ + // FileSummarizer.ts + + const fs = require('fs'); + + function summarizeFilesInDirectorySync(directory: string): string[] { + return fs.readdirSync(directory).map((fileName: string) => ({ + fileName, + directory, + })); + } + + //export default summarizeFilesInDirectorySync; // For sake of compilation + + // ------------------------------------------------------------------------------------ + // __mocks__/fs.js + + const path = require('path'); + + const mockedFS: MockedFS = jest.genMockFromModule('fs'); + + let mockFiles: any = Object.create(null); + function __setMockFiles(newMockFiles: MockFiles): void { + mockFiles = Object.create(null); + for(const file in newMockFiles) { + const dir: string = path.dirname(file); + + if (!mockFiles[dir]) { + mockFiles[dir] = []; + } + mockFiles[dir].push(path.basename(file)); + } + } + + function readdirSync(directoryPath: string): string[] { + return mockFiles[directoryPath] || []; + } + + mockedFS.readdirSync = readdirSync; + mockedFS.__setMockFiles = __setMockFiles; + + //export = mockedFS; // For sake of compilation + // ------------------------------------------------------------------------------------ + // __tests__/FileSummarizer-test.js + + jest.mock('fs'); + + describe('listFilesInDirectorySync', () => { + const MOCK_FILE_INFO: MockFiles = { + '/path/to/file1.js': 'console.log("file1 contents");', + '/path/to/file2.txt': 'file2 contents', + }; + + beforeEach(() => { + // Set up some mocked out file info before each test + (require('fs') as MockedFS).__setMockFiles(MOCK_FILE_INFO); + }); + + it('includes all files in the directory in the summary', () => { + const FileSummarizer: (dir: string) => string[] = require('../FileSummarizer'); + const fileSummary = FileSummarizer('/path/to'); + + expect(fileSummary.length).toBe(2); + }); + }); +}); diff --git a/jest/jest.d.ts b/jest/jest.d.ts index b2484dfcc5..506bd6533d 100644 --- a/jest/jest.d.ts +++ b/jest/jest.d.ts @@ -1,122 +1,79 @@ -// Type definitions for Jest 0.9.0 +// Type definitions for Jest 15.1.1 // Project: http://facebook.github.io/jest/ -// Definitions by: Asana +// Definitions by: Asana , Ivo Stratev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare function afterEach(fn: jest.EmptyFunction): void; -declare function beforeEach(fn: jest.EmptyFunction): void; -declare function describe(name: string, fn: jest.EmptyFunction): void; -declare var it: jest.It; -declare function pit(name: string, fn: jest.EmptyFunction): void; - -declare function xdescribe(name: string, fn: jest.EmptyFunction): void; -declare function xit(name: string, fn: jest.EmptyFunction): void; - +declare function afterEach(fn: () => any): void; +declare function beforeEach(fn: () => any): void; +declare function describe(name: string, fn: () => any): void; declare function expect(actual: any): jest.Matchers; +declare function it(name: string, fn: () => any): void; +declare function fit(name: string, fn: () => any): void; -interface NodeRequire { - requireActual(moduleName: string): any; -} +declare function test(name: string, fn: () => any): void; +declare function xdescribe(name: string, fn: () => any): void; +declare function xit(name: string, fn: () => any): void; declare namespace jest { - function addMatchers(matchers: CustomMatcherFactories): void; - function autoMockOff(): void; - function autoMockOn(): void; - function clearAllTimers(): void; - function currentTestPath(): string; - function disableAutomock(): void; - function fn(implementation?: Function): Mock; - function dontMock(moduleName: string): void; - function genMockFromModule(moduleName: string): Mock; - function mock(moduleName: string, factory?: Function): void; - function runAllTicks(): void; - function runAllTimers(): void; - function runOnlyPendingTimers(): void; - function setMock(moduleName: string, moduleExports: T): void; - function unmock(moduleName: string): void; - - interface EmptyFunction { - (): void; - } - interface Matchers { + lastCalledWith(...args: any[]): boolean; not: Matchers; - toThrow(expected?: any): boolean; - toThrowError(expected?: any): boolean; toBe(expected: any): boolean; - toEqual(expected: any): boolean; - toBeFalsy(): boolean; - toBeTruthy(): boolean; - toBeNull(): boolean; - toBeDefined(): boolean; - toBeUndefined(): boolean; - toMatch(expected: RegExp): boolean; - toContain(expected: string): boolean; - toBeCloseTo(expected: number, delta: number): boolean; - toBeGreaterThan(expected: number): boolean; - toBeLessThan(expected: number): boolean; toBeCalled(): boolean; toBeCalledWith(...args: any[]): boolean; - lastCalledWith(...args: any[]): boolean; + toBeCloseTo(expected: number, delta: number): boolean; + toBeDefined(): boolean; + toBeFalsy(): boolean; + toBeGreaterThan(expected: number): boolean; + toBeGreaterThanOrEqual(expected: number): boolean; + toBeLessThan(expected: number): boolean; + toBeLessThanOrEqual(expected: number): boolean; + toBeNull(): boolean; + toBeTruthy(): boolean; + toBeUndefined(): boolean; + toContain(expected: string): boolean; + toEqual(expected: any): boolean; + toMatch(expected: RegExp): boolean; + toMatchSnapshot(): boolean; + toThrow(): boolean; + toThrowError(expected: string | RegExp): boolean; + toThrowError(expected: TFunction): boolean; } - - interface It { - (name: string, fn: EmptyFunction): void; - only(name: string, fn: EmptyFunction): void; - } - - interface Mock { - new (): T; - (...args: any[]): any; // TODO please fix this line! added for TypeScript 1.1.0-1 https://github.com/DefinitelyTyped/DefinitelyTyped/pull/2932 - mock: MockContext; - mockClear(): void; - mockImplementation(fn: Function): Mock; - mockImpl(fn: Function): Mock; - mockReturnThis(): Mock; - mockReturnValue(value: any): Mock; - mockReturnValueOnce(value: any): Mock; - } - + interface MockContext { calls: any[][]; instances: T[]; } - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomMatcherFactories { - [index: string]: CustomMatcherFactory; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomMatcherFactory { - (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface MatchersUtil { - equals(a: any, b: any, customTesters?: Array): boolean; - contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; - buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomEqualityTester { - (first: any, second: any): boolean; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomMatcher { - compare(actual: T, expected: T): CustomMatcherResult; - compare(actual: any, expected: any): CustomMatcherResult; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomMatcherResult { - pass: boolean; - message: string; + interface Mock { + new (): T; + (...args: any[]): any; // Making Mock Callable and fixing: Value of type 'Mock' is not callable. + mock: MockContext; + mockClear(): void; + mockImplementation(fn: Function): Mock; + mockImplementationOnce(fn: Function): Mock; + mockReturnThis(): Mock; + mockReturnValue(value: any): Mock; + mockReturnValueOnce(value: any): Mock; } + + function clearAllTimers(): void; + function disableAutomock(): void; + function enableAutomock(): void; + function fn(implementation?: Function): Mock; + function isMockFunction(fn: Function): boolean; + function genMockFromModule(moduleName: string): T; + function mock(moduleName: string, factory?: Function, options?: {virtual: boolean}): void; + function resetModules(): void; + function runAllTicks(): void; + function runAllTimers(): void; + function runOnlyPendingTimers(): void; + function setMock(moduleName: string, moduleExports: T): void; + function unmock(moduleName: string): void; + function useFakeTimers(): void; + function useRealTimers(): void; // taken from Jasmine which takes from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() interface ArrayLike { @@ -124,3 +81,8 @@ declare namespace jest { [n: number]: T; } } + +interface NodeRequire { + requireActual(moduleName: string): any; + requireMock(moduleName: string): any; +} From 7c50d2c7a7d11b0e6e76508b59b359b4ae4e558c Mon Sep 17 00:00:00 2001 From: "Dmitry A. Efimenko" Date: Thu, 15 Sep 2016 10:20:57 -0700 Subject: [PATCH 514/844] added prop options and func timeFormatter added property `options`, which can be found in [the code](https://github.com/joewalnes/smoothie/blob/15fc4b62f5b23c8d5dd1784c820ae73f341626e6/smoothie.js#L270). Even though it's not mentioned in the docs, it useful to be able to access these options after chart is initialized when you want to change appearance in real tme. added function `timeFormatter`, which is mentioned in [right here, in the definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/smoothie/smoothie.d.ts#L127) and can be found in [the code](https://github.com/joewalnes/smoothie/blob/15fc4b62f5b23c8d5dd1784c820ae73f341626e6/smoothie.js#L795) --- smoothie/smoothie.d.ts | 4 ++++ 1 file changed, 4 insertions(+) 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; } } From 4e6cafda2c6c59c87ebe394f039c63aa35f312ac Mon Sep 17 00:00:00 2001 From: Derek Finlinson Date: Thu, 15 Sep 2016 11:49:51 -0600 Subject: [PATCH 515/844] Fix openQuickCreate signature Fixed openQuickCreate signature which had a callback as the first parameter when it should just return a XrmPromise. --- xrm/xrm.d.ts | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/xrm/xrm.d.ts b/xrm/xrm.d.ts index 824c91ba0c..2e4856e0c7 100644 --- a/xrm/xrm.d.ts +++ b/xrm/xrm.d.ts @@ -160,8 +160,6 @@ declare namespace Xrm /** * Opens quick create. * - * @param {Function} callback The function that will be called when a record is created. This - * function is passed a LookupValue object as a parameter. * @param {string} entityLogicalName The logical name of the entity to create. * @param {Page.LookupValue} createFromEntity (Optional) Designates a record that will provide default values * based on mapped attribute values. @@ -170,10 +168,9 @@ declare namespace Xrm * error. */ openQuickCreate( - callback: ( recordReference: Page.LookupValue ) => void, entityLogicalName: string, createFromEntity?: Page.LookupValue, - parameters?: Utility.OpenParameters ): void; + parameters?: Utility.OpenParameters ): Async.XrmPromise; /** * Opens an entity form. @@ -1477,11 +1474,11 @@ declare namespace Xrm * Use this method to asynchronously retrieve the enabled business process flows that the user can switch to for an * entity. * - * @param {Function} callbackFunction The callback function must accept a parameter that contains an object with + * @param {Function} callbackFunction The callback function must accept a parameter that contains an object with * dictionary properties where the name of the property is the Id of the * business process flow and the value of the property is the name of the * business process flow. - * + * * The enabled processes are filtered according to the user’s privileges. The * list of enabled processes is the same ones a user can see in the UI if they * want to change the process manually. @@ -1501,7 +1498,7 @@ declare namespace Xrm * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event * handler pipeline. The execution context is automatically * set to be the first parameter passed to the event handler. - * + * * Use a reference to a named function rather than an * anonymous function if you may later want to remove the * event handler. @@ -1515,7 +1512,7 @@ declare namespace Xrm * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event * handler pipeline. The execution context is automatically * set to be the first parameter passed to the event handler. - * + * * Use a reference to a named function rather than an * anonymous function if you may later want to remove the * event handler. @@ -2587,4 +2584,4 @@ declare namespace XrmEnum SystemView = 1039, UserView = 4230 } -} \ No newline at end of file +} From 34cc2ed80a7fe9f75c36d0f89c336234991fe320 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Fri, 16 Sep 2016 02:15:14 +0800 Subject: [PATCH 516/844] Create pug-test.ts --- pug/pug-test.ts | 103 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 pug/pug-test.ts diff --git a/pug/pug-test.ts b/pug/pug-test.ts new file mode 100644 index 0000000000..5ba7d9ad06 --- /dev/null +++ b/pug/pug-test.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; + }); + } +} From 1b803f972a8edfcd8341520f195e7354fa091ec2 Mon Sep 17 00:00:00 2001 From: feitzi Date: Fri, 16 Sep 2016 12:49:30 +0200 Subject: [PATCH 517/844] Added definition file for randomColor --- randomColor/randomColor-tests.ts | 2 ++ randomColor/randomColor.d.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 randomColor/randomColor-tests.ts create mode 100644 randomColor/randomColor.d.ts diff --git a/randomColor/randomColor-tests.ts b/randomColor/randomColor-tests.ts new file mode 100644 index 0000000000..274768ebc1 --- /dev/null +++ b/randomColor/randomColor-tests.ts @@ -0,0 +1,2 @@ +/// + diff --git a/randomColor/randomColor.d.ts b/randomColor/randomColor.d.ts new file mode 100644 index 0000000000..e439e2d77d --- /dev/null +++ b/randomColor/randomColor.d.ts @@ -0,0 +1,30 @@ +// Type definitions for randomColor 0.4.1 +// Project: https://github.com/davidmerfield/randomColor +// Definitions by: Mathias Feitzinger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace RandomColor { + + interface RandomColorStatic { + + () : string; + + (options : randomColorOptions): string; + +} + +interface randomColorOptions { + hue? : string; + luminosity? : string; + count? : string; + seed?: string; + format?: string; + } +} + + +declare var randomColor: RandomColor.RandomColorStatic; + +declare module 'randomColor' { + export = randomColor; +} \ No newline at end of file From 300d30753459bbd6fe6b53b61e44e21e3669fc97 Mon Sep 17 00:00:00 2001 From: feitzi Date: Fri, 16 Sep 2016 12:58:59 +0200 Subject: [PATCH 518/844] added test for randomColor --- randomColor/randomColor-tests.ts | 38 ++++++++++++++++++++++++++++++++ randomColor/randomColor.d.ts | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/randomColor/randomColor-tests.ts b/randomColor/randomColor-tests.ts index 274768ebc1..69b617615e 100644 --- a/randomColor/randomColor-tests.ts +++ b/randomColor/randomColor-tests.ts @@ -1,2 +1,40 @@ /// +// Returns a hex code for an attractive color +randomColor(); + +// Returns an array of ten green colors +randomColor({ + count: 10, + hue: 'green' +}); + +// Returns a hex code for a light blue +randomColor({ + luminosity: 'light', + hue: 'blue' +}); + +// Returns a hex code for a 'truly random' color +randomColor({ + luminosity: 'random', + hue: 'random' +}); + +// Returns a bright color in RGB +randomColor({ + luminosity: 'bright', + format: 'rgb' // e.g. 'rgb(225,200,20)' +}); + +// Returns a dark RGB color with random alpha +randomColor({ + luminosity: 'dark', + format: 'rgba' // e.g. 'rgba(9, 1, 107, 0.6482447960879654)' +}); + +// Returns a light HSL color with random alpha +randomColor({ + luminosity: 'light', + format: 'hsla' // e.g. 'hsla(27, 88.99%, 81.83%, 0.6450211517512798)' +}); \ No newline at end of file diff --git a/randomColor/randomColor.d.ts b/randomColor/randomColor.d.ts index e439e2d77d..81f43a0228 100644 --- a/randomColor/randomColor.d.ts +++ b/randomColor/randomColor.d.ts @@ -16,7 +16,7 @@ declare namespace RandomColor { interface randomColorOptions { hue? : string; luminosity? : string; - count? : string; + count? : string | number; seed?: string; format?: string; } From 1175068a71da6baf10fffaf08df4fa8c32ebb6a9 Mon Sep 17 00:00:00 2001 From: feitzi Date: Fri, 16 Sep 2016 13:14:08 +0200 Subject: [PATCH 519/844] styling for randomColor --- randomColor/randomColor.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/randomColor/randomColor.d.ts b/randomColor/randomColor.d.ts index 81f43a0228..1c52f39be1 100644 --- a/randomColor/randomColor.d.ts +++ b/randomColor/randomColor.d.ts @@ -10,7 +10,6 @@ declare namespace RandomColor { () : string; (options : randomColorOptions): string; - } interface randomColorOptions { @@ -22,7 +21,6 @@ interface randomColorOptions { } } - declare var randomColor: RandomColor.RandomColorStatic; declare module 'randomColor' { From c81e53488b9053b9d211b2a3bf381a9c6ed58ce1 Mon Sep 17 00:00:00 2001 From: Humberto Machado Date: Fri, 16 Sep 2016 08:41:30 -0300 Subject: [PATCH 520/844] Add stack property to Router. Used to list all configured routes in express Router instance --- express-serve-static-core/express-serve-static-core.d.ts | 4 ++++ 1 file changed, 4 insertions(+) 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 e80ffa85a9..f0cc9669ad 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -97,6 +97,10 @@ declare module "express-serve-static-core" { use: IRouterHandler & IRouterMatcher; route(prefix: PathParams): IRoute; + /** + * Stack of configured routes + */ + stack: any[]; } interface IRoute { From 2d08ea98c9e95f23754c5cd6f33598a444d7ef13 Mon Sep 17 00:00:00 2001 From: Humberto Machado Date: Fri, 16 Sep 2016 08:48:06 -0300 Subject: [PATCH 521/844] Fix comment --- express-serve-static-core/express-serve-static-core.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 f0cc9669ad..624ed5ae5d 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -1052,7 +1052,7 @@ declare module "express-serve-static-core" { routes: any; /** - * Using to all registered routes in Express Application + * Used to get all registered routes in Express Application */ _router: any; } From 406a8d2a5a58061bd2b76b3d42945156a258bc72 Mon Sep 17 00:00:00 2001 From: Daryl LaBar Date: Fri, 16 Sep 2016 09:58:31 -0400 Subject: [PATCH 522/844] Added the new 8.0 AutoComplete Features. Since this in in 8.0 only and beyond, created 7.1 versions of Xrm.d.ts and tests.ts based on previous version. --- xrm/xrm-7.1.d.ts | 2590 ++++++++++++++++++++++++++++++++++++++++++ xrm/xrm-7.1.tests.ts | 137 +++ xrm/xrm-tests.ts | 33 + xrm/xrm.d.ts | 112 +- 4 files changed, 2871 insertions(+), 1 deletion(-) create mode 100644 xrm/xrm-7.1.d.ts create mode 100644 xrm/xrm-7.1.tests.ts diff --git a/xrm/xrm-7.1.d.ts b/xrm/xrm-7.1.d.ts new file mode 100644 index 0000000000..824c91ba0c --- /dev/null +++ b/xrm/xrm-7.1.d.ts @@ -0,0 +1,2590 @@ +// Type definitions for Microsoft Dynamics xRM API v7.1 +// Project: http://www.microsoft.com/en-us/download/details.aspx?id=44567 +// Definitions by: David Berry , Matt Ngan , Markus Mauch , Daryl LaBar +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var Xrm: Xrm.XrmStatic; +declare function GetGlobalContext(): Xrm.Context; + +interface Window +{ + Xrm: Xrm.XrmStatic; + GetGlobalContext(): Xrm.Context; +} + +declare namespace Xrm +{ + /** + * Static xRM object. + */ + export interface XrmStatic + { + /** + * Provides a namespace container for the context, data and ui objects. + */ + Page: { + /** + * Provides methods to retrieve information specific to an organization, a user, or parameters passed to a page. + */ + context: Context; + + /** + * Provides methods to work with the form. + */ + data: Data; + + /** + * Contains properties and methods to retrieve information about the user interface as well as collections for several subcomponents of the form. + */ + ui: Ui; + + /** + * Gets all attributes. + * + * @return An array of attributes. + */ + getAttribute(): Page.Attribute[]; + + /** + * Gets an attribute matching attributeName. + * + * @tparam T An Attribute type. + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + getAttribute( attributeName: string ): T; + + /** + * Gets an attribute matching attributeName. + * + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + getAttribute( attributeName: string ): Page.Attribute; + + /** + * Gets an attribute by index. + * + * @param {number} index The attribute index. + * + * @return The attribute. + */ + getAttribute( index: number ): Page.Attribute; + + /** + * Gets an attribute. + * + * @param {Collection.MatchingDelegate{Attribute}} delegateFunction A matching delegate function + * + * @return An array of attribute. + */ + getAttribute( delegateFunction: Collection.MatchingDelegate ): Page.Attribute[]; + + /** + * Gets all controls. + * + * @return An array of controls. + */ + getControl(): Page.Control[]; + + /** + * Gets a control matching controlName. + * + * @tparam T A Control type + * @param {string} controlName Name of the control. + * + * @return The control. + */ + getControl( controlName: string ): T; + + /** + * Gets a control matching controlName. + * + * @param {string} controlName Name of the control. + * + * @return The control. + */ + getControl( controlName: string ): Page.Control; + + /** + * Gets a control by index. + * + * @param {number} index The control index. + * + * @return The control. + */ + getControl( index: number ): Page.Control; + + /** + * Gets a control. + * + * @param {Collection.MatchingDelegate{Control}} delegateFunction A matching delegate function. + * + * @return An array of control. + */ + getControl( delegateFunction: Collection.MatchingDelegate ): Page.Control[]; + } + + /** + * Provides a container for useful functions not directly related to the current page. + */ + Utility: { + /** + * Displays an alert dialog, with an "OK" button. + * + * @param {string} message The message. + * @param {function()} onCloseCallback The "OK" callback. + */ + alertDialog( message: string, onCloseCallback: () => void ): void; + + /** + * Displays a confirmation dialog, with "OK" and "Cancel" buttons. + * + * @param {string} message The message. + * @param {function()} yesCloseCallback The "OK" callback. + * @param {function()} noCloseCallback The "Cancel" callback. + */ + confirmDialog( message: string, yesCloseCallback: () => void, noCloseCallback: () => void ): void; + + /** + * Query if 'entityType' is an Activity entity. + * + * @param {string} entityType Type of the entity. + * + * @return true if the entity is an Activity, false if not. + */ + isActivityType( entityType: string ): boolean; + + /** + * Opens quick create. + * + * @param {Function} callback The function that will be called when a record is created. This + * function is passed a LookupValue object as a parameter. + * @param {string} entityLogicalName The logical name of the entity to create. + * @param {Page.LookupValue} createFromEntity (Optional) Designates a record that will provide default values + * based on mapped attribute values. + * @param {OpenParameters} parameters (Optional) A dictionary object that passes extra query string + * parameters to the form. Invalid query string parameters will cause an + * error. + */ + openQuickCreate( + callback: ( recordReference: Page.LookupValue ) => void, + entityLogicalName: string, + createFromEntity?: Page.LookupValue, + parameters?: Utility.OpenParameters ): void; + + /** + * Opens an entity form. + * + * @param {string} name The entity's logical name. + * @param {string} id (Optional) The unique identifier for the record. + * @param {FormParameters} parameters (Optional) A dictionary object that passes extra query string parameters to the form. + * @param {WindowOptions} windowOptions (Optional) Options for controlling the window. + */ + openEntityForm( name: string, id?: string, parameters?: Utility.FormOpenParameters, windowOptions?: Utility.WindowOptions ): void; + + /** + * Opens an HTML Web Resource in a new browser window. + * + * @param {string} webResourceName Name of the HTML web resource. Can be used to pass URL + * parameters. See Remarks. + * @param {string} webResourceData (Optional) Data to pass into the Web Resource's data parameter. + * It is advised to use encodeURIcomponent() to encode the value. + * @param {number} width (Optional) The width of the new window. + * @param {number} height (Optional) The height of the new window. + * + * @return A Window reference, containing the opened Web Resource. + * + * @remarks This function will not work with Microsoft Dynamics CRM for tablets. + * Valid WebResource URL Parameters: typename + * type + * id + * orgname + * userlcid + * data (identical to this method's webResourceData parameter) + * formid + */ + openWebResource( webResourceName: string, webResourceData?: string, width?: number, height?: number ): Window; + } + } + + /** + * Client Types for Xrm.Page.context.getClient(). + */ + export type Client = "Web" | "Outlook" | "Mobile"; + /** + * Client States for Xrm.Page.context.getClientState(). + */ + export type ClientState = "Online" | "Offline"; + /** + * Themes for Xrm.Page.context.getCurrentTheme(). + */ + export type Theme = "default" | "Office12Blue" | "Office14Silver"; + + /** + * Interface for the client context. + */ + export interface ClientContext + { + /** + * Returns a value to indicate which client the script is executing in. + * + * @return The client, as either "Web", "Outlook", or "Mobile" + */ + getClient(): Client; + + /** + * Gets client's current state. + * + * @return The client state, as either "Online" or "Offline" + */ + getClientState(): ClientState; + } + + /** + * Interface for the xRM application context. + */ + interface Context + { + /** + * The client's context instance. + */ + client: ClientContext; + + /** + * Gets client's base URL for Dynamics CRM + * + * @return The client's base URL + * @remarks For Dynamics CRM On-Premises: http(s)://server/org + * For Dynamics CRM Online: https://org.crm.dynamics.com + * For Dynamics CRM for Outlook (Offline): http://localhost:2525 + */ + getClientUrl(): string; + + /** + * Gets current styling theme. + * + * @return The name of the current theme, as either "default", "Office12Blue", or "Office14Silver" + * + * @remarks This function does not work with Dynamics CRM for tablets. + */ + getCurrentTheme(): Theme; + + /** + * Gets whether automatic save is enabled. + * + * @return true if automatic saving is enabled, otherwise false. + */ + getIsAutoSaveEnabled(): boolean; + + /** + * Gets organization's LCID (language code). + * + * @return The organization language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getOrgLcid(): number; + + /** + * Gets organization's unique name. + * + * @return The organization's unique name. + * + * @remarks This value can be found on the Developer Resources page within Dynamics CRM + */ + getOrgUniqueName(): string; + + /** + * Gets query string parameters. + * + * @return The query string parameters, in a dictionary object representing name and value pairs. + */ + getQueryStringParameters(): { [index: string]: any }; + + /** + * Returns the difference between the local time and Coordinated Universal Time (UTC). + * + * @return The time zone offset, in minutes. + */ + getTimeZoneOffsetMinutes(): number; + + /** + * Gets user's unique identifier. + * + * @return The user's identifier in Guid format. + * + * @remarks Example: "{B05EC7CE-5D51-DF11-97E0-00155DB232D0}" + */ + getUserId(): string; + + /** + * Gets user's LCID (language code). + * + * @return The user's language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getUserLcid(): number; + + /** + * Gets the name of the current user. + * + * @return The user's name. + */ + getUserName(): string; + + /** + * Gets all user security roles. + * + * @return An array of user role identifiers, in Guid format. + * + * @remarks Example: ["cf4cc7ce-5d51-df11-97e0-00155db232d0"] + */ + getUserRoles(): string[]; + + /** + * Prefixes the current organization's unique name to a string; typically a URL path. + * + * @param {string} sPath Local pathname of the resource. + * + * @return A path string with the organization name. + * + * @remarks Format: "/"+ OrgName + sPath + */ + prependOrgName( sPath: string ): string; + } + + /** + * Interface for the Xrm.Page.data object. + */ + export interface Data + { + /** + * Asynchronously refreshes data on the form, without reloading the page. + * + * @param {boolean} save true to save the record, after the refresh. + * + * @return An Async.XrmPromise. + */ + refresh( save: boolean ): Async.XrmPromise; + + /** + * Asynchronously saves the record. + * + * @return An Async.XrmPromise. + */ + save(): Async.XrmPromise; + + /** + * The record context of the form. + */ + entity: Page.Entity; + + /** + * The process API for Xrm.Page.data. + * + * @remarks This member may be undefined when Process Flows are not used by the current entity. + */ + process: Page.data.ProcessManager; + } + + /** + * Interface for the Xrm.Page.ui object. + */ + export interface Ui + { + /** + * Clears the form notification described by uniqueId. + * + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, otherwise false. + */ + clearFormNotification( uniqueId: string ): boolean; + + /** + * Closes the form. + */ + close(): void; + + /** + * Gets form type. + * + * @return The form type. + * + * @remarks Values returned are: 0 Undefined + * 1 Create + * 2 Update + * 3 Read Only + * 4 Disabled + * 6 Bulk Edit + * Deprecated values are 5 (Quick Create), and 11 (Read Optimized) + */ + getFormType(): XrmEnum.FormType; + + /** + * Gets view port height. + * + * @return The view port height, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + getViewPortHeight(): number; + + /** + * Gets view port width. + * + * @return The view port width, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + getViewPortWidth(): number; + + /** + * Re-evaluates the ribbon's configured EnableRules + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + refreshRibbon(): void; + + setFormNotification(message: string, level: Page.ui.FormNotificationLevel | string, uniqueId: string ): boolean; + + process: Page.data.ProcessManager; + + /** + * A reference to the collection of controls on the form. + */ + controls: Collection.ItemCollection; + + /** + * The form selector API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + formSelector: Page.FormSelector; + + /** + * The navigation API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + navigation: Page.Navigation; + + /** + * A reference to the collection of tabs on the form. + */ + tabs: Collection.ItemCollection; + } + + /** + * A definition module for asynchronous interface declarations. + */ + export module Async + { + /** + * Called when the operation is successful. + */ + export type SuccessCallbackDelegate = () => void; + + /** + * Called when the operation fails. + * + * @param {number} errorCode The error code. + * @param {string} message The message. + */ + export type ErrorCallbackDelegate = ( errorCode: number, message: string ) => void; + + /** + * Interface for Xrm.Page.data promises. + */ + export interface XrmPromise + { + /** + * A basic 'then' promise. + * + * @param {SuccessCallbackDelegate} successCallback The success callback. + * @param {ErrorCallbackDelegate} errorCallback The error callback. + */ + then( successCallback: SuccessCallbackDelegate, errorCallback: ErrorCallbackDelegate ): void; + } + } + + /** + * A definition module for collection interface declarations. + */ + export module Collection + { + /** + * Interface for a matching delegate. + * + * @tparam T Generic type parameter. + */ + export interface MatchingDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + * + * @return true if the item matches, false if it does not. + */ + ( item: T, index?: number ): boolean; + } + + /** + * Interface for iterative delegate. + * + * @tparam T Generic type parameter. + */ + export interface IterativeDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + */ + ( item: T, index?: number ): void; + } + + /** + * Interface for an item collection. + * + * @tparam T Generic type parameter. + */ + export interface ItemCollection + { + /** + * Applies an operation to all items in this collection. + * + * @param {IterativeDelegate{T}} delegate An iterative delegate function + */ + forEach( delegate: IterativeDelegate ): void; + + /** + * Gets. + * + * @param {MatchingDelegate{T}} delegate A matching delegate function + * + * @return A T[] whose members have been validated by delegate. + */ + get( delegate: MatchingDelegate ): T[]; + + /** + * Gets the item given by the index. + * + * @param {number} itemNumber The item number to get. + * + * @return The T in the itemNumber-th place. + */ + get( itemNumber: number ): T; + + /** + * Gets the item given by the key. + * + * @param {string} itemName The item name to get. + * + * @return The T matching the key itemName. + * + * @see {@link Xrm.Page.Control.getName()} for Control-naming schemes. + */ + get( itemName: string ): T; + + /** + * Gets the entire array of T. + * + * @return A T[]. + */ + get(): T[]; + + /** + * Gets the length of the collection. + * + * @return The length. + */ + getLength(): number; + } + } + + /** + * The Xrm.Page API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Page + { + /** + * Requirement Level for Xrm.Page.Attribute.getRequiredLevel() and Xrm.Page.Attribute.setRequiredLevel(). + */ + export type RequirementLevel = "none" | "recommended" | "required"; + /** + * Save Modes for Xrm.Page.Entity.save(). + */ + export type SaveMode = "saveandclose" | "saveandnew"; + /** + * Status for Xrm.Page.Stage.getStatus(). + */ + export type Status = "active" | "inactive"; + /** + * Submit Mode for Xrm.Page.Attribute.getSubmitMode() and Xrm.Page.Attribute.setSubmitMode(). + */ + export type SubmitMode = "always" | "dirty" | "never"; + + /** + * Interface for a CRM Business Process Flow instance. + */ + export interface Process + { + /** + * Returns the unique identifier of the process. + * + * @return The identifier for this process, in GUID format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Returns the name of the process. + * + * @return The name. + */ + getName(): string; + + /** + * Returns an collection of stages in the process. + * + * @return The stages. + */ + getStages(): Collection.ItemCollection; + + /** + * Returns a boolean value to indicate if the process is rendered. + * + * @return true if the process is rendered, false if not. + */ + isRendered(): boolean; + } + + /** + * Interface for CRM Business Process Flow stages. + */ + export interface Stage + { + /** + * Returns an object with a getValue method which will return the integer value of the business process flow + * category. + * + * @return The stage category. + */ + getCategory(): { getValue(): XrmEnum.StageCategory }; + + /** + * Returns the logical name of the entity associated with the stage. + * + * @return The entity name. + */ + getEntityName(): string; + + /** + * Returns the unique identifier of the stage. + * + * @return The identifier of the Stage, in GUID format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Returns the name of the stage. + * + * @return The name. + */ + getName(): string; + + /** + * Returns the status of the stage. + * + * @return The status. + * + * @remarks This method will return either "active" or "inactive". + */ + getStatus(): Status; + + /** + * Returns a collection of steps in the stage. + * + * @return An array of Step. + */ + getSteps(): Step[]; + } + + export interface Step + { + /** + * Returns the logical name of the attribute associated to the step. + * + * @return The attribute. + * + * @remarks Some steps don’t contain an attribute value. + */ + getAttribute(): string; + + /** + * Returns the name of the step. + * + * @return The name. + */ + getName(): string; + + /** + * Returns whether the step is required in the business process flow. + * + * @return true if required, false if not. + * + * @remarks Returns true if the step is marked as required in the Business Process Flow editor; otherwise, false. + * There is no connection between this value and the values you can change in the Xrm.Page.data.entity + * attribute RequiredLevel methods. + */ + isRequired(): boolean; + } + + /** + * Interface for the event context. + */ + export interface EventContext + { + /** + * Gets the Xrm context. + * + * @return The Xrm context. + */ + getContext(): Context; + + /** + * Gets the handler's depth, which is the order in which the handler is executed. + * + * @return The depth, a 0-based index. + */ + getDepth(): number; + + /** + * Gets save-event arguments. + * + * @return The event arguments. + * + * @remarks Returns null for all but the "save" event. + */ + getEventArgs(): SaveEventArguments; + + /** + * Gets a reference to the object for which event occurred. + * + * @return The event source. + */ + getEventSource(): Attribute | Control | Entity; + + /** + * Gets the shared variable with the specified key. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * + * @return The shared variable. + * + * @remarks Used to pass values between handlers of an event. + */ + getSharedVariable( key: string ): T; + + /** + * Sets a shared variable. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * @param {T} value The value. + * + * @remarks Used to pass values between handlers of an event. + */ + setSharedVariable( key: string, value: T ): void; + } + + /** + * Interface for a context-sensitive handler. + */ + export interface ContextSensitiveHandler + { + /** + * @param {EventContext} context The context. + */ + ( context?: EventContext ): void; + } + + /** + * Base interface for UI elements. + */ + export interface UiElement + { + /** + * Gets the label. + * + * @return The label. + */ + getLabel(): string; + + /** + * Gets the visibility state. + * + * @return true if the tab is visible, otherwise false. + */ + getVisible(): boolean; + + /** + * Sets the label. + * + * @param {string} label The label. + */ + setLabel( label: string ): void; + + /** + * Sets the visibility state. + * + * @param {boolean} visible true to show, false to hide. + */ + setVisible( visible: boolean ): void; + } + + /** + * Interface for focusable UI elements. + */ + export interface UiFocusable + { + /** + * Sets focus on the element. + */ + setFocus(): void; + } + + /** + * Interface for a Lookup value. + */ + export interface LookupValue + { + /** + * The identifier. + */ + id: string; + + /** + * The name + */ + name?: string; + + /** + * Type of the entity. + */ + entityType: string; + } + + /** + * Interface for an OptionSet value. + */ + export interface OptionSetValue + { + /** + * The label text. + */ + text: string; + + /** + * The value, as a number + */ + value: number; + } + + /** + * Interface for a privilege. + */ + export interface Privilege + { + /** + * true if the user can read. + */ + canRead: boolean; + + /** + * true if the user can update. + */ + canUpdate: boolean; + + /** + * true if the user can create. + */ + canCreate: boolean; + } + + /** + * Interface for an Entity attribute. + */ + export interface Attribute + { + /** + * Adds a handler to be called when the attribute's value is changed. + * + * @param {ContextSensitiveHandler} handler The function reference. + */ + addOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Fire all "on change" event handlers. + */ + fireOnChange(): void; + + /** + * Gets attribute type. + * + * @return The attribute's type name. + * + * @remarks Values returned are: boolean + * datetime + * decimal + * double + * integer + * lookup + * memo + * money + * optionset + * string + */ + getAttributeType(): string; + + /** + * Gets the attribute format. + * + * @return The format of the attribute. + * + * @see {@link getAttributeType()} + * + * @remarks Values returned are: date (datetime) + * datetime (datetime) + * duration (integer) + * email (string) + * language (optionset) + * none (integer) + * phone (string) + * text (string) + * textarea (string) + * tickersymbol (string) + * timezone (optionset) + * url (string) + */ + getFormat(): string; + + /** + * Gets a boolean value indicating whether this Attribute has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the logical name of the attribute. + * + * @return The logical name. + */ + getName(): string; + + /** + * Gets a reference to the record context of this attribute. + * + * @return The parent record context. + */ + getParent(): Entity; + + /** + * Gets the current level of requirement for the attribute. + * + * @return The required level, as either "none", "required", or "recommended" + */ + getRequiredLevel(): RequirementLevel; + + /** + * Gets current submit mode for the attribute. + * + * @return The submit mode, as either "always", "never", or "dirty" + * + * @remarks The default value is "dirty" + */ + getSubmitMode(): SubmitMode; + + /** + * Gets the current user's privileges for the attribute. + * + * @return The user privileges. + */ + getUserPrivilege(): Privilege; + + /** + * Removes the handler from the "on change" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Sets the required level. + * + * @param {string} requirementLevel The requirement level, as either "none", "required", or "recommended" + */ + setRequiredLevel(requirementLevel: RequirementLevel | string): void; + + /** + * Sets the submit mode. + * + * @param {string} submitMode The submit mode, as either "always", "never", or "dirty". + * + * @remarks The default value is "dirty" + */ + setSubmitMode(submitMode: SubmitMode | string): void; + + /** + * A collection of all the controls on the form that interface with this attribute. + */ + controls: Collection.ItemCollection; + } + + /** + * Interface for a Number attribute. + * + * @sa Attribute + */ + export interface NumberAttribute extends Attribute + { + /** + * Gets the maximum value allowed. + * + * @return The maximum value allowed. + */ + getMax(): number; + + /** + * Gets the minimum value allowed. + * + * @return The minimum value allowed. + */ + getMin(): number; + + /** + * Gets the attribute's configured precision. + * + * @return The total number of allowed decimal places. + */ + getPrecision(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface for a String attribute. + * + * @sa Attribute + */ + export interface StringAttribute extends Attribute + { + /** + * Gets maximum length allowed. + * + * @return The maximum length allowed. + * + * @remarks The email form's "Description" attribute does not have the this method. + */ + getMaxLength(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): string; + + /** + * Sets the value. + * + * @param {string} value The value. + * + * @remarks A String field with the {@link Attribute.getFormat|email} format enforces email + * address formatting. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: string ): void; + } + + /** + * Common interface for enumeration attributes (OptionSet and Boolean). + * + * @sa Attribute + */ + export interface EnumAttribute extends Attribute + { + /** + * Gets the initial value of the attribute. + * + * @return The initial value. + * @remarks Valid for optionset and boolean attribute types + */ + getInitialValue(): number | boolean; + } + + /** + * Interface for a Boolean attribute. + * + * @sa EnumAttribute + */ + export interface BooleanAttribute extends EnumAttribute + { + /** + * Gets the value. + * + * @return true if it succeeds, false if it fails. + */ + getValue(): boolean; + + /** + * Sets the value. + * + * @param {boolean} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: boolean ): void; + } + + /** + * Interface for a Date attribute. + * + * @sa Attribute + */ + export interface DateAttribute extends Attribute + { + /** + * Gets the value. + * + * @return The value. + */ + getValue(): Date; + + /** + * Sets the value. + * + * @param {Date} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: Date ): void; + } + + /** + * Interface an OptionSet attribute. + * + * @sa EnumAttribute + */ + export interface OptionSetAttribute extends EnumAttribute + { + /** + * Gets the option matching a value. + * + * @param {number} value The enumeration value of the option desired. + * + * @return The option. + */ + getOption( value: number ): OptionSetValue; + + /** + * Gets the option matching a label. + * + * @param {string} label The label of the option desired. + * + * @return The option. + */ + getOption( label: string ): OptionSetValue; + + /** + * Gets all of the options. + * + * @return An array of options. + */ + getOptions(): OptionSetValue[]; + + /** + * Gets selected option. + * + * @return The selected option. + */ + getSelectedOption(): OptionSetValue; + + /** + * Gets the label of the currently selected option. + * + * @return The current value's label. + */ + getText(): string; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks The getOptions() method returns option values as strings. You must use parseInt + * to convert them to numbers before you can use those values to set the value of an + * OptionSet attribute. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface a Lookup attribute. + * + * @sa Attribute + */ + export interface LookupAttribute extends Attribute + { + /** + * Gets a boolean value indicating whether the Lookup is a multi-value PartyList. + * + * @return true the attribute is a PartyList, otherwise false. + */ + getIsPartyList(): boolean; + + /** + * Gets the value. + * + * @return An array of LookupValue. + */ + getValue(): LookupValue[]; + + /** + * Sets the value. + * + * @param {LookupValue[]} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: LookupValue[] ): void; + } + + /** + * Interface for the form's record context, Xrm.Page.data.entity + */ + export interface Entity + { + /** + * Adds a handler to be called when the record is saved. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + addOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Gets an serialized-XML string representing data that will be passed to the server upon saving + * the record. + * + * @return The XML in string format. + * + * @remarks This function does not work with Microsoft Dynamics CRM for tablets. Example: + * "Contoso55555425 + * 555-1234". + */ + getDataXml(): string; + + /** + * Gets entity's logical name. + * + * @return The logical name. + */ + getEntityName(): string; + + /** + * Gets the record's unique identifier. + * + * @return The identifier, in Guid format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Gets a boolean value indicating whether the record has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the record's primary attribute value. + * + * @return The primary attribute value. + * + * @remarks The value for this attribute is used when links to the record are displayed. + */ + getPrimaryAttributeValue(): string; + + /** + * Removes the handler from the "on save" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Saves the record. + * + * @remarks When using quick create forms in the web application the saveandnew option is not + * applied. It will always work as if saveandclose were used. Quick create forms in + * Microsoft Dynamics CRM for tablets will apply the saveandnew behavior. + */ + save(): void; + + /** + * Saves the record with the given save mode. + * + * @param {string} saveMode (Optional) the save mode to save, as either "saveandclose" or + * "saveandnew". + */ + save( saveMode: SaveMode | string): void; + + /** + * The collection of attributes for the record. + */ + attributes: Collection.ItemCollection; + } + + /** + * Interface for save event arguments. + */ + export interface SaveEventArguments + { + /** + * Gets save mode, as an integer. + * + * @return The save mode. + * @remarks Values returned are: 1 Save + * 2 Save and Close + * 59 Save and New + * 70 AutoSave (Where enabled; can be used with an OnSave handler + * to conditionally disable auto-saving) + * 58 Save as Completed (Activities) + * 5 Deactivate + * 6 Reactivate + * 47 Assign (All user- or team-owned entities) + * 7 Send (Email) + * 16 Qualify (Lead) + * 15 Disqualify (Lead) + */ + getSaveMode(): XrmEnum.SaveMode; + + /** + * Returns a boolean value to indicate if the record's save has been prevented. + * + * @return true if saving is prevented, otherwise false. + */ + isDefaultPrevented(): boolean; + + /** + * Prevents the save operation from being submitted to the server. + * @remarks All remaining "on save" handlers will continue execution. + */ + preventDefault(): void; + } + + /** + * Module for the Xrm.Page.data API. + */ + export module data + { + /** + * Interface for the Xrm.Page.data.process API. + */ + export interface ProcessManager + { + /** + * Returns a Process object representing the active process. + * + * @return current active process. + */ + getActiveProcess(): Process; + + /** + * Set a Process as the active process. + * + * @param {string} processId The Id of the process to make the active process. + * @param {function} callbackFunction (Optional) a function to call when the operation is complete. + */ + setActiveProcess( processId: string, callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Returns a Stage object representing the active stage. + * + * @return current active stage. + */ + getActiveStage(): Stage; + + /** + * Set a stage as the active stage. + * + * @param {string} stageId the Id of the stage to make the active stage. + * @param {function} callbackFunction (Optional) a function to call when the operation is complete. + */ + setActiveStage( stageId: string, callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Use this method to get a collection of stages currently in the active path with methods to interact with the + * stages displayed in the business process flow control. The active path represents stages currently rendered in + * the process control based on the branching rules and current data in the record. + * + * @return A collection of all completed stages, the currently active stage, and the predicted set of future stages + * based on satisfied conditions in the branching rule. This may be a subset of the stages returned with + * Xrm.Page.data.process.getActiveProcess because it will only include those stages which represent a valid + * transition from the current stage based on branching that has occurred in the process. + */ + getActivePath(): Collection.ItemCollection; + + /** + * Use this method to asynchronously retrieve the enabled business process flows that the user can switch to for an + * entity. + * + * @param {Function} callbackFunction The callback function must accept a parameter that contains an object with + * dictionary properties where the name of the property is the Id of the + * business process flow and the value of the property is the name of the + * business process flow. + * + * The enabled processes are filtered according to the user’s privileges. The + * list of enabled processes is the same ones a user can see in the UI if they + * want to change the process manually. + */ + getEnabledProcesses( callbackFunction: ( enabledProcesses: ProcessDictionary ) => void ): void; + + /** + * Use this method to get the currently selected stage. + * + * @return The currently selected stage. + */ + getSelectedStage(): Stage; + + /** + * Use this to add a function as an event handler for the OnStageChange event so that it will be called when the + * business process flow stage changes. + * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event + * handler pipeline. The execution context is automatically + * set to be the first parameter passed to the event handler. + * + * Use a reference to a named function rather than an + * anonymous function if you may later want to remove the + * event handler. + */ + addOnStageChange( handler: ContextSensitiveHandler ): void; + + /** + * Use this to add a function as an event handler for the OnStageSelected event so that it will be called + * when a business process flow stage is selected. + * + * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event + * handler pipeline. The execution context is automatically + * set to be the first parameter passed to the event handler. + * + * Use a reference to a named function rather than an + * anonymous function if you may later want to remove the + * event handler. + */ + addOnStageSelected(handler: ContextSensitiveHandler): void; + + /** + * Use this to remove a function as an event handler for the OnStageChange event. + * + * @param {ContextSensitiveHandler} handler If an anonymous function is set using the addOnStageChange method it + * cannot be removed using this method. + */ + removeOnStageChange(handler: ContextSensitiveHandler): void; + + /** + * Use this to remove a function as an event handler for the OnStageChange event. + * + * @param {ContextSensitiveHandler} handler If an anonymous function is set using the addOnStageChange method it + * cannot be removed using this method. + */ + removeOnStageSelected( handler: ContextSensitiveHandler ): void; + + /** + * Progresses to the next stage. + * + * @param {ProcessCallbackDelegate} callbackFunction (Optional) A function to call when the operation is + * complete. + */ + moveNext( callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Moves to the previous stage. + * + * @param {ProcessCallbackDelegate} callbackFunction (Optional) A function to call when the operation is + * complete. + */ + movePrevious( callbackFunction?: ProcessCallbackDelegate ): void; + } + + /** + * Called when process change methods have completed. + * + * @param {string} status The result of the process change operation. + * @remarks Values returned are: success (The operation succeeded.) + * crossEntity (The previous stage is for a different entity.) + * beginning (The active stage is the first stage of the active path.) + * invalid (The operation failed because the selected stage isn’t the same + * as the active stage.) + * unreachable (The stage exists on a different path.) + */ + export type ProcessCallbackDelegate = ( status: string ) => void; + + /** + * Represents a key-value pair, where the key is the Process Flow's ID, and the value is the name thereof. + */ + export type ProcessDictionary = { [index: string]: string }; + } + + /** + * Interface for Xrm.Page.ui controls. + * + * @sa UiElement + */ + export interface Control extends UiElement, UiFocusable + { + /** + * Clears the notification identified by uniqueId. + * + * @param {string} uniqueId (Optional) Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks If the uniqueId parameter is not used, the current notification shown will be removed. + */ + clearNotification( uniqueId?: string ): boolean; + + /** + * Gets the control's type. + * + * @return The control type. + * @remarks Values returned are: standard + * iframe + * lookup + * optionset + * subgrid + * webresource + * notes + * timercontrol + * kbsearch (CRM Online Only, use parature.d.ts) + */ + getControlType(): string; + + /** + * Gets a boolean value, indicating whether the control is disabled. + * + * @return true if it is disabled, otherwise false. + */ + getDisabled(): boolean; + + /** + * Gets the name of the control on the form. + * + * @return The name of the control. + * + * @remarks The name assigned to a control is not determined until the form loads. Changes to + * the form may change the name assigned to a given control. + * When you use the control getName method the name of the first control will be the + * same as the name of the attribute. The second instance of a control for that + * attribute will be "1". The pattern +N + * will continue for each additional control added to the form for a specific + * attribute. When a form displays a business process flow control in the header, + * additional controls will be added for each attribute that is displayed in the + * business process flow. These controls have a unique name like the following: + * header_process_. + */ + getName(): string; + + /** + * Gets a reference to the Section parent of the control. + * + * @return The parent Section. + */ + getParent(): Section; + + /** + * Sets the state of the control to either enabled, or disabled. + * + * @param {boolean} disabled true to disable, false to enable. + */ + setDisabled( disabled: boolean ): void; + + /** + * Sets a control-local notification message. + * + * @param {string} message The message. + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks When this method is used on Microsoft Dynamics CRM for tablets a red "X" icon + * appears next to the control. Tapping on the icon will display the message. + */ + setNotification( message: string, uniqueId: string ): boolean; + } + + /** + * Interface for a standard control. + * + * @sa Control + */ + export interface StandardControl extends Control + { + /** + * Gets the control's bound attribute. + * + * @tparam T An Attribute type. + * + * @return The attribute. + */ + getAttribute(): T; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): Attribute; + } + + /** + * Interface for a Date control. + * + * @sa StandardControl + */ + export interface DateControl extends StandardControl + { + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): DateAttribute; + + /** + * Gets the status of the time-of-day component of the Date control. + * + * @return true if the time is shown, otherwise false. + */ + getShowTime(): boolean; + + /** + * Sets the visibility of the time component of the Date control. + * + * @param {boolean} showTimeValue true to show, false to hide the time value. + */ + setShowTime( showTimeValue: boolean ): void; + } + + /** + * Interface for a Lookup control. + * + * @sa StandardControl + */ + export interface LookupControl extends StandardControl + { + /** + * Adds a handler to the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + addPreSearch( handler: ContextSensitiveHandler ): void; + + /** + * Adds an additional custom filter to the lookup, with the "AND" filter operator. + * Can only be used within a "pre search" event handler + * + * @sa addPreSearch + * + * @param {string} filter Specifies the filter, as a serialized FetchXML + * "filter" node. + * @param {string} entityLogicalName (Optional) The logical name of the entity. + * + * @remarks If entityLogicalName is not specified, the filter will be applied to all entities + * valid for the Lookup control. + * Example filter: + * + * + */ + addCustomFilter( filter: string, entityLogicalName?: string ): void; + + /** + * Adds a custom view for the Lookup dialog. + * + * @param {string} viewId Unique identifier for the view, in Guid format. + * @param {string} entityName Name of the entity. + * @param {string} viewDisplayName Name of the view to display. + * @param {string} fetchXml The FetchXML query for the view's contents, serialized as a string. + * @param {string} layoutXml The Layout XML, serialized as a string. + * @param {boolean} isDefault true, to treat this view as default. + * + * @remarks Cannot be used on "Owner" Lookup controls. + * The viewId is never saved to CRM, but must be unique across available views. Generating + * a new value can be accomplished with a {@link http://www.guidgen.com/|Guid generator}. + * Example viewId value: "{00000000-0000-0000-0000-000000000001}" + * Layout XML Reference: {@link http://msdn.microsoft.com/en-us/library/gg334522.aspx} + */ + addCustomView( viewId: string, entityName: string, viewDisplayName: string, fetchXml: string, layoutXml: string, isDefault: boolean ): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): LookupAttribute; + + /** + * Gets the unique identifier of the default view. + * + * @return The default view, in Guid format. + * + * @remarks Example: "{00000000-0000-0000-0000-000000000000}" + */ + getDefaultView(): string; + + /** + * Removes the handler from the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + removePreSearch( handler: () => void ): void; + + /** + * Sets the Lookup's default view. + * + * @param {string} viewGuid Unique identifier for the view. + * + * @remarks Example viewGuid value: "{00000000-0000-0000-0000-000000000000}" + */ + setDefaultView( viewGuid: string ): void; + } + + /** + * Interface for an OptionSet control. + * + * @sa StandardControl + */ + export interface OptionSetControl extends StandardControl + { + /** + * Adds an option. + * + * @param {OptionSetValue} option The option. + * @param {number} index (Optional) zero-based index of the option. + * + * @remarks This method does not check that the values within the options you add are valid. + * If index is not provided, the new option will be added to the end of the list. + */ + addOption( option: OptionSetValue, index?: number ): void; + + /** + * Clears all options. + */ + clearOptions(): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): OptionSetAttribute; + + /** + * Removes the option matching the value. + * + * @param {number} value The value. + */ + removeOption( value: number ): void; + } + + /** + * Interface for a CRM grid control. + * + * @sa Control + */ + export interface GridControl extends Control + { + /** + * Use this method to add event handlers to the GridControl's OnLoad event. + * + * @param {Function} handler The event handler. + */ + addOnLoad( handler: () => void ): void; + + /** + * This method returns context information about the GridControl. + * + * @return The context type. + */ + getContextType(): XrmEnum.GridControlContext; + + /** + * Use this method to get the logical name of the entity data displayed in the grid. + * + * @return The entity name. + */ + getEntityName(): string; + + /** + * Use this method to get access to the Grid available in the GridControl. + * + * @return The grid. + */ + getGrid(): ui.Grid; + + /** + * Use this method to get access to the ViewSelector available for the GridControl when it is configured to display views. + * + * @return The view selector. + */ + getViewSelector(): ui.ViewSelector; + + /** + * Refreshes the sub grid. + * + * @remarks Not available during the "on load" event of the form. + */ + refresh(): void; + + /** + * Use this method to remove event handlers from the GridControl's OnLoad event. + * + * @param {Function} handler The handler. + */ + removeOnLoad( handler: () => void ): void; + } + + /** + * Interface for a framed control, which is either a Web Resource or an Iframe. + * + * @sa Control + * + * @remarks An Iframe control provides additional methods, so use {@link IframeControl} where + * appropriate. Silverlight controls should use {@link SilverlightControl}. + */ + export interface FramedControl extends Control + { + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLIFrameElement; + + /** + * Gets the URL value of the control. + * + * @return The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getSrc(): string; + + /** + * Sets the URL value of the control. + * + * @param {string} src The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setSrc( src: string ): void; + } + + /** + * Interface for an Iframe control. + * + * @sa FramedControl + */ + export interface IframeControl extends FramedControl + { + /** + * Gets initial URL defined for the Iframe. + * + * @return The initial URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getInitialUrl(): string; + } + + /** + * Interface for a Silverlight control. + * + * @sa Control + */ + export interface SilverlightControl extends Control + { + /** + * Gets the query string value passed to Silverlight. + * + * @return The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getData(): string; + + /** + * Sets the query string value passed to Silverlight. + * + * @param {string} data The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setData( data: string ): void; + + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLObjectElement; + } + + /** + * Interface for a form tab. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface Tab extends UiElement, UiFocusable + { + /** + * Gets display state of the tab. + * + * @return The display state, as either "expanded" or "collapsed" + */ + getDisplayState(): ui.DisplayState; + + /** + * Gets the name of the tab. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.ui parent of the tab. + * + * @return The parent. + */ + getParent(): Ui; + + /** + * Sets display state of the tab. + * + * @param {string} displayState Display state of the tab, as either "expanded" or "collapsed" + */ + setDisplayState(displayState: ui.DisplayState | string ): void; + + /** + * A reference to the collection of form sections within this tab. + */ + sections: Collection.ItemCollection
    ; + } + + /** + * Interface for a form section. + * + * @sa UiElement + */ + export interface Section extends UiElement + { + /** + * Gets the name of the section. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.Tab parent of this item. + * + * @return The parent. + */ + getParent(): Tab; + + /** + * A reference to the collection of controls within this tab. + */ + controls: Collection.ItemCollection; + } + + /** + * Module for Xrm.Page.ui API. + */ + export module ui + { + /** + * Form Notification Levels for Xrm.Ui.setFormNotification(). + */ + export type FormNotificationLevel = "ERROR" | "INFO" | "WARNING"; + + /** + * Display States for Xrm.ui.ProcessMonitor.setDisplayState(). + */ + export type DisplayState = "collapsed" | "expanded"; + + /** + * Interface for Xrm.Page.ui.process API + */ + export interface ProcessManager + { + /** + * Sets display state of the process flow control. + * + * @param {string} displayState Display state of the process flow control, as either "expanded" or "collapsed" + */ + setDisplayState(displayState: ui.DisplayState ): void; + + /** + * Sets the visibility state. + * + * @param {boolean} visible true to show, false to hide. + */ + setVisible( visible: boolean ): void; + } + + /** + * Interface for a grid. Use Grid methods to access information about data in the grid. Grid is returned by the + * GridControl.getGrid method. + */ + export interface Grid + { + /** + * Returns a collection of every GridRow in the Grid. + * + * @return The rows. + */ + getRows(): Collection.ItemCollection; + + /** + * Returns a collection of every selected GridRow in the Grid. + * + * @return The selected rows. + */ + getSelectedRows(): Collection.ItemCollection; + + /** + * Returns the total number of records in the Grid. + * + * @return The total record count. + */ + getTotalRecordCount(): number; + } + + /** + * Interface for a grid row. Use the GridRow.getData method to access the GridRowData. A collection of GridRow is + * returned by Grid.getRows and Grid.getSelectedRows methods. + */ + export interface GridRow + { + /** + * Returns the GridRowData for the GridRow. + * + * @return The data. + */ + getData(): GridRowData; + } + + /** + * Interface for grid row data. Use the GridRowData.getEntity method to access the GridEntity. GridRowData is + * returned by the GridRow.getData method. + */ + export interface GridRowData + { + /** + * Returns the GridEntity for the GridRowData. + * + * @return The entity. + */ + getEntity(): GridEntity; + } + + /** + * Interface for a grid entity. Use the GridEntity methods to access data about the specific records in the rows. + * GridEntity is returned by the GridRowData.getEntity method. + */ + export interface GridEntity + { + /** + * Returns the logical name for the record in the row. + * + * @return The entity name. + */ + getEntityName(): string; + + /** + * Returns a LookupValue that references this record. + * + * @return The entity reference. + */ + getEntityReference(): LookupValue; + + /** + * Returns the id for the record in the row. + * + * @return The identifier of the GridEntity, in GUID format. + * + * @remarks Example return: "{00000000-0000-0000-0000-000000000000}" + */ + getId(): string; + + /** + * Returns the primary attribute value for the record in the row. (Commonly the name.) + * + * @return The primary attribute value. + */ + getPrimaryAttributeValue(): string; + } + + /** + * Interface for the view selector. Use the ViewSelector methods to get or set information about the view selector + * of the grid control. + */ + export interface ViewSelector + { + /** + * Use this method to get a reference to the current view. + * + * @return The current view. + */ + getCurrentView(): ViewSelectorItem; + + /** + * Use this method to determine whether the view selector is visible. + * + * @return true if visible, false if not. + */ + isVisible(): boolean; + + /** + * Use this method to set the current view. + * + * @param {ViewSelectorItem} viewSelectorItem The view selector item. + */ + setCurrentView( viewSelectorItem: ViewSelectorItem ): void; + } + + /** + * Interface for a view selector item. This object contains data that identifies a view. Use this as a parameter to + * the ViewSelector.setCurrentView method. + */ + export interface ViewSelectorItem + { + /** + * Returns a LookupValue that references this view. + * + * @return The entity reference. + */ + getEntityReference(): LookupValue; + } + } + + /** + * Interface for a navigation item. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface NavigationItem extends UiElement, UiFocusable + { + /** + * Gets the name of the item. + * + * @return The identifier. + */ + getId(): string; + } + + /** + * Interface for Xrm.Page.ui.navigation. + */ + export interface Navigation + { + /** + * A reference to the collection of available navigation items. + */ + items: Collection.ItemCollection; + } + + /** + * Interface for an entity's form selector item. + */ + export interface FormItem + { + /** + * Gets the unique identifier of the form. + * + * @return The identifier, in Guid format. + */ + getId(): string; + + /** + * Gets the label for the form. + * + * @return The label. + */ + getLabel(): string; + + /** + * Navigates the user to this form. + */ + navigate(): void; + } + + /** + * Interface for the form selector API. + */ + export interface FormSelector + { + /** + * Gets current form. + * + * @return The current item. + * + * @remarks When only one form is available this method will return null. + */ + getCurrentItem(): FormItem; + + /** + * A reference to the collection of available forms. + */ + items: Collection.ItemCollection; + } + } + + /** + * An definition module for URL-based, CRM component parameters. + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export module Url + { + /** + * Command Bar Display options for Xrm.Url.FormOpenParameters.cmdbar, Xrm.Url.ViewOpenParameters.cmdbar, and Xrm.Utility.FormOpenParameters.cmdbar. + */ + export type CmdBarDisplay = "true" | "false"; + /** + * Navigation Bar Display options for Xrm.Url.FormOpenParameters.navbar, Xrm.Url.ViewOpenParameters.navbar, and Xrm.Utility.FormOpenParameters.navbar. + */ + export type NavBarDisplay = "entity" | "off" | "on"; + /** + * Report Open Action options for Xrm.Url.ReportOpenParameters.actions. + */ + export type ReportAction = "filter" | "run"; + + /** + * Interface for defining parameters on a request to open a form with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entityrecord" is required in + * the URL, for forms. Example: "pagetype=entityrecord" + */ + export interface FormOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * Additional parameters can be provided to the request. This can only be used to provide + * default field values for the form, or pass data to custom parameters that have been + * customized for the form. See example below for setting the selected form. + * + * @remarks Example: encodeURIComponent( "formid={8c9f3e6f-7839-e211-831e-00155db7d98f}" ); + */ + extraqs?: string; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: CmdBarDisplay; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: NavBarDisplay; + } + + /** + * Interface for defining parameters on a request to open a view with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entitylist" is required in + * the URL, for views. Example: "pagetype=entitylist" + */ + export interface ViewOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * The unique identifier of a view, in Guid format, which is valid for the entity described by + * {@link etn}. + */ + viewid: string; + + /** + * The type of view identified by {@link viewid}. + * + * @remarks Accepted values are: 1039 System View + * 4230 User View. + */ + viewtype: XrmEnum.ViewType; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: CmdBarDisplay; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: NavBarDisplay; + } + + /** + * Interface for defining parameters of a request to open a dialog with rundialog.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface DialogOpenParameters + { + /** + * The unique identifier of the dialog, in Guid format, which is valid for the entity described + * by: {@link EntityName} + */ + DialogId: string; + + /** + * The logical name of the entity. + */ + EntityName: string; + + /** + * The unique identifier for the targeted record. + */ + ObjectId: string; + } + + /** + * Interface for defining parameters of a request to open a report with viewer.apsx (as with + * window.open). Useful for parsing out the keys and values into a string of the format: + * "&key=value" + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface ReportOpenParameters + { + /** + * The action to perform, as either "run" or "filter". + * + * @remarks "run" Executes the report with default filters. + * "filter" Presents the user with the filter editor, and a "Run Report" button. + */ + action: ReportAction; + + /** + * The file name of the report. For out-of-box reports, this parameter enables context-sensitive + * help. + */ + helpID?: string; + + /** + * The unique identifier, held in the report's 'reportid' attribute, in Guid format. + */ + id: string; + } + } + + /** + * The Xrm.Utility API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Utility + { + export interface OpenParameters + { + /** + * Additional parameters can be provided to the request, by overloading + * this object with additional key and value pairs. This can only be used + * to provide default field values for the form, or pass data to custom + * parameters that have been customized for the form. + */ + [index: string]: string; + } + + /** + * Interface for defining parameters on a Xrm.Utility.openEntityForm() request. + */ + export interface FormOpenParameters extends OpenParameters + { + /** + * The identifier of the form to use, when several are available. + */ + formid: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: Url.NavBarDisplay; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: Url.CmdBarDisplay; + } + + /** + * Interface for window options. + */ + export interface WindowOptions + { + /** + * Direct the form to open in a new window. + */ + openInNewWindow: boolean; + } + } +} + +declare namespace XrmEnum +{ + /** + * Enumeration of entity form states/types. + */ + export const enum FormType + { + Undefined = 0, + Create = 1, + Update = 2, + ReadOnly = 3, + Disabled = 4, + BulkEdit = 6 + } + + /** + * Enumeration of entity form save modes. + */ + export const enum SaveMode + { + Save = 1, + SaveAndClose = 2, + SaveAndNew = 59, + AutoSave = 70, + SaveAsCompleted = 58, + Deactivate = 5, + Reactivate = 6, + Assign = 47, + Send = 7, + Qualify = 16, + Disqualify = 15 + } + + /** + * Enumeration of stage categories. + */ + export const enum StageCategory + { + Qualify = 0, + Develop = 1, + Propose = 2, + Close = 3, + Identify = 4, + Research = 5, + Resolve = 6 + } + + /** + * Enumeration of grid control context resolutions. + */ + export const enum GridControlContext + { + Unknown = 0, + RibbonContextForm = 1, + RibbonContextListing = 2, + FormContextUnrelated = 3, + FormContextRelated = 4 + } + + /** + * An enumeration for view types. + */ + export const enum ViewType + { + SystemView = 1039, + UserView = 4230 + } +} \ No newline at end of file diff --git a/xrm/xrm-7.1.tests.ts b/xrm/xrm-7.1.tests.ts new file mode 100644 index 0000000000..f3f4576b02 --- /dev/null +++ b/xrm/xrm-7.1.tests.ts @@ -0,0 +1,137 @@ +/// +/// + +/// Demonstrate usage in the browser's window object + +window.Xrm.Utility.alertDialog( "message", () => {} ); +parent.Xrm.Page.context.getOrgLcid(); + +/// Demonstrate clientglobalcontext.d.ts + +function _getContext() +{ + var errorMessage = "Context is not available."; + if ( typeof GetGlobalContext != "undefined" ) + { return GetGlobalContext(); } + else + { + if ( typeof Xrm != "undefined" ) + { + return Xrm.Page.context; + } + else { throw new Error( errorMessage ); } + } +} + +var crmContext = _getContext(); + +/// Demonstrate iterator typing + +var grids = Xrm.Page.getControl(( control ) => +{ + return control.getControlType() === "subgrid"; +}); + +var selectedGridReferences: Xrm.Page.LookupValue[] = []; + +/// Demonstrate iterator typing with v7.1 additions + +grids.forEach(( gridControl: Xrm.Page.GridControl ) => +{ + gridControl.getGrid().getSelectedRows().forEach(( row ) => + { + selectedGridReferences.push( row.getData().getEntity().getEntityReference() ); + }) +}); + +/// Demonstrate generic overload vs typecast + +var lookupAttribute = Xrm.Page.getControl( "customerid" ); +var lookupAttribute2 = Xrm.Page.getControl( "customerid" ); + +/// Demonstrate ES6 String literal syntax + +lookupAttribute.addCustomFilter( ` + +`, "account" ); + +lookupAttribute.addPreSearch(() => { alert( "A search was performed." ); }); + +/// Demonstrate strong-typed attribute association with strong-typed control + +var lookupValues = lookupAttribute.getAttribute().getValue(); + +if ( lookupValues !== null ) + if ( !lookupValues[0].id || !lookupValues[0].entityType ) + throw new Error("Invalid value in Lookup control."); + +/// Demonstrate v7.0 BPF API + +if (Xrm.Page.data.process != null) + Xrm.Page.data.process.moveNext(( status ) => { alert( `Process moved forward with status: ${status}` ) }); + +/// Demonstrate v7.1 Quick Create form + +Xrm.Utility.openQuickCreate(( newRecord ) => { alert( `Newly created record Id: ${newRecord.id}` ); }, "account" ); + +/// Make all controls visible. + +Xrm.Page.ui.controls.forEach(( control ) => { control.setVisible( true ); }); + +/// Make all tabs and sections visible. + +Xrm.Page.ui.tabs.forEach(( tab ) => +{ + tab.setVisible( true ); + + tab.sections.forEach(( section ) => + { + section.setVisible( true ); + }); +}); + +/// Demonstrate OnSave event context. + +Xrm.Page.data.entity.addOnSave(( context ) => +{ + var eventArgs = context.getEventArgs(); + + if ( eventArgs.getSaveMode() === XrmEnum.SaveMode.AutoSave || eventArgs.getSaveMode() === XrmEnum.SaveMode.SaveAndClose ) + eventArgs.preventDefault(); +}); + +/// Demonstrate ES6 String literal with templates + +alert( `The current form type is: ${Xrm.Page.ui.getFormType() }` ); + +alert( `The current entity type is: ${Xrm.Page.data.entity.getEntityName() }` ); + +/// Demonstrate Optionset Value as int in Turbo Forms + +var optionSetAttribute = Xrm.Page.getAttribute( "statuscode" ); +const optionValue: number = optionSetAttribute.getOptions()[0].value; + +/// Demonstrate Control.setFocus(); + +optionSetAttribute.controls.get(0).setFocus(); + +/// Demonstrate setFormNotification + +var level: Xrm.Page.ui.FormNotificationLevel; +level = "ERROR"; +Xrm.Page.ui.setFormNotification("Test", level, "uniqueId"); + +/// Demonstrate Requirement Level and Submit Mode both via string parameters and String Literal Types + +let requirementLevel: Xrm.Page.RequirementLevel = "none"; +let requirementLevelString = "none"; +let submitMode: Xrm.Page.SubmitMode = "always"; +let submitModeString = "always"; + +let attribute = Xrm.Page.getAttribute("customerid"); +attribute.setSubmitMode(submitMode); +attribute.setSubmitMode(submitMode); +attribute.setRequiredLevel(requirementLevel); +attribute.setRequiredLevel(requirementLevelString); + + diff --git a/xrm/xrm-tests.ts b/xrm/xrm-tests.ts index f3f4576b02..8c4f52c2c7 100644 --- a/xrm/xrm-tests.ts +++ b/xrm/xrm-tests.ts @@ -134,4 +134,37 @@ attribute.setSubmitMode(submitMode); attribute.setRequiredLevel(requirementLevel); attribute.setRequiredLevel(requirementLevelString); +/// Demonstrate v8 AutoComplete + +let autoCompleteControl = Xrm.Page.getControl("name"); +var userInput = autoCompleteControl.getValue(); +const accountResult = { }; +const resultSet: Xrm.Page.AutoCompleteResultSet = { + results: new Array() as Xrm.Page.AutoCompleteResult[], + commands: { + id: "sp_commands", + label: "Learn More", + action() { + // Specify what you want to do when the user + // clicks the "Learn More" link at the bottom + // of the auto-completion list. + // For this sample, we are just opening a page + // that provides information on working with + // accounts in CRM. + window.open("http://www.microsoft.com/en-us/dynamics/crm-customer-center/create-or-edit-an-account.aspx"); + } + } as Xrm.Page.AutoCompleteCommand +}; +resultSet.results.push({ + id: 0, + fields: ["A. Datum Corporation"] +}); +autoCompleteControl.addOnKeyPress(() => { }); +autoCompleteControl.fireOnKeyPress(); +autoCompleteControl.removeOnKeyPress(() => {}); +autoCompleteControl.showAutoComplete(resultSet); +autoCompleteControl.hideAutoComplete(); + + + diff --git a/xrm/xrm.d.ts b/xrm/xrm.d.ts index 824c91ba0c..7942b53adb 100644 --- a/xrm/xrm.d.ts +++ b/xrm/xrm.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Microsoft Dynamics xRM API v7.1 +// Type definitions for Microsoft Dynamics xRM API v8.0 // Project: http://www.microsoft.com/en-us/download/details.aspx?id=44567 // Definitions by: David Berry , Matt Ngan , Markus Mauch , Daryl LaBar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -868,6 +868,66 @@ declare namespace Xrm setFocus(): void; } + /** + * Interface for Result value of AutoCompleteResultSet + */ + export interface AutoCompleteResult { + /** + * The Identifier + */ + id: string|number; + + /** + * Url of the icon to display + */ + icon?: string; + + /** + * Display value(s) for this auto-complete option + */ + fields: string[]; + } + + /** + * Interface for command of AutoCompleteResultSet. This is displayed at the bottom of the auto complete view + */ + export interface AutoCompleteCommand { + /** + * The Identifier + */ + id: string; + + /** + * Url of the icon to display + */ + icon?: string; + + /** + * Label to display at the bottom of the auto complete view + */ + label: string; + + /** + * Action to perform when user clicks on label + */ + action(): void; + } + + /** + * Interface for showAutoComplete argument + */ + export interface AutoCompleteResultSet { + /** + * Results to show + */ + results: AutoCompleteResult[]; + + /** + * Command to show/execute at the bottom of the results displayed + */ + commands?: AutoCompleteCommand; + } + /** * Interface for a Lookup value. */ @@ -1685,6 +1745,56 @@ declare namespace Xrm getAttribute(): Attribute; } + /** + * Interace for Auto Lookup Control + * This is not an Entity Lookup, but a control that supports AutoComplete/KeyPress Events (Text) + * NOTE * This interface is not supported for CRM mobile clients (phones or tablets) and the interactive service hub. It is only available for Updated entities. + * + * @sa StandardControl + */ + export interface AutoLookupControl extends StandardControl { + /** + * Use this to add a function as an event handler for the keypress event so that the function is called when you type a character in the specific text or number field. + * For a sample JavaScript code that uses the addOnKeyPress method to configure the auto-completion experience, see Sample: Auto-complete in CRM controls. + * + * @param {ContextSensitiveHandler} handler The function reference. + */ + addOnKeyPress(handler: ContextSensitiveHandler): void; + + /** + * Use this to manually fire an event handler that you created for a specific text or number field to be executed on the keypress event. + */ + fireOnKeyPress(): void; + + /** + * Gets the latest value in a control as the user types characters in a specific text or number field. + * This method helps you to build interactive experiences by validating data and alerting users as they type characters in a control. + * The getValue method is different from the attribute getValue method because the control method retrieves the value from the control + * as the user is typing in the control as opposed to the attribute getValue method that retrieves the value after the user commits (saves) the field. + */ + getValue(): string; + + /** + * Hides the auto-completion drop-down list configured for a specific text field + */ + hideAutoComplete(): void; + + /** + * Use this to remove an event handler for a text or number field that you added using addOnKeyPress. + * + * Remarks: If an anonymous function is set using addOnKeyPress, it can’t be removed using this method. + * @param {ContextSensitiveHandler} handler The function reference. + */ + removeOnKeyPress(handler: ContextSensitiveHandler): void; + + /** + * Shows upt to 10 matching strings in a drop-down list as users press keys to type charactrer in a specific text field. + * On selecting an item in the drop-down list, the value in the text field changes to the selected item, the drop-down list disappears, and the OnChange event for the text field is invoked + * @param resultSet + */ + showAutoComplete(resultSet: AutoCompleteResultSet): void; + } + /** * Interface for a Date control. * From b5e3b1987f6cbee9627bdbd845e0e9bf71325125 Mon Sep 17 00:00:00 2001 From: Ulrich Buchgraber Date: Fri, 16 Sep 2016 18:17:22 +0200 Subject: [PATCH 523/844] Simplify typings by employing "polymorphic this types" for clone()/copy() methods Note: This also solves TS 2.0 --strictNullChecks errors. --- threejs/three-canvasrenderer.d.ts | 1 - threejs/three.d.ts | 221 +++++++++--------------------- 2 files changed, 63 insertions(+), 159 deletions(-) diff --git a/threejs/three-canvasrenderer.d.ts b/threejs/three-canvasrenderer.d.ts index 2d2d9e4930..7dba387da9 100644 --- a/threejs/three-canvasrenderer.d.ts +++ b/threejs/three-canvasrenderer.d.ts @@ -17,7 +17,6 @@ declare namespace THREE { color: Color; program(context: any, color: Color): void; - clone(): SpriteCanvasMaterial; } export interface CanvasRendererParameters { diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 9e70f1e898..830edbf864 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -461,9 +461,6 @@ declare namespace THREE { * @param vector point to look at */ lookAt(vector: Vector3): void; - - clone(): Camera; - copy(camera?: Camera): Camera; } export class CubeCamera extends Object3D { @@ -540,8 +537,6 @@ declare namespace THREE { updateProjectionMatrix(): void; setViewOffset(fullWidth: number, fullHeight: number, offsetX: number, offsetY: number, width: number, height: number): void; clearViewOffset(): void; - clone(): OrthographicCamera; - copy(source: OrthographicCamera): OrthographicCamera; toJSON(meta?: any): any; } @@ -646,7 +641,6 @@ declare namespace THREE { * Updates the camera projection matrix. Must be called after change of parameters. */ updateProjectionMatrix(): void; - clone(): PerspectiveCamera; toJSON(meta?: any): any; // deprecated @@ -682,8 +676,8 @@ declare namespace THREE { count: number; setDynamic(dynamic: boolean): BufferAttribute; - clone(): BufferAttribute; - copy(source: BufferAttribute): BufferAttribute; + clone(): this; + copy(source: this): this; copyAt(index1: number, attribute: BufferAttribute, index2: number): BufferAttribute; copyArray(array: ArrayLike): BufferAttribute; copyColorsArray(colors: {r: number, g: number, b: number}[]): BufferAttribute; @@ -703,7 +697,6 @@ declare namespace THREE { setXY(index: number, x: number, y: number): BufferAttribute; setXYZ(index: number, x: number, y: number, z: number): BufferAttribute; setXYZW(index: number, x: number, y: number, z: number, w: number): BufferAttribute; - clone(): BufferAttribute; length: number; // deprecated, use count } @@ -834,8 +827,8 @@ declare namespace THREE { toNonIndexed(): BufferGeometry; toJSON(): any; - clone(): BufferGeometry; - copy(source: BufferGeometry): BufferGeometry; + clone(): this; + copy(source: this): this; /** * Disposes the object from memory. @@ -1086,8 +1079,8 @@ declare namespace THREE { */ materialIndex: number; - clone(): Face3; - copy(source: Face3): Face3; + clone(): this; + copy(source: this): this; } export class Face4 extends Face3 {} // deprecated, use Face3 @@ -1308,9 +1301,9 @@ declare namespace THREE { /** * Creates a new clone of the Geometry. */ - clone(): Geometry; + clone(): this; - copy(source: Geometry): Geometry; + copy(source: this): this; /** * Removes The object from memory. @@ -1343,9 +1336,6 @@ declare namespace THREE { constructor(data: ArrayLike, itemSize: number, meshPerAttribute?: number); meshPerAttribute: number; - - clone(): InstancedBufferAttribute; - copy(source: InstancedBufferAttribute): InstancedBufferAttribute; } /** @@ -1358,8 +1348,6 @@ declare namespace THREE { maxInstancedCount: number; addGroup(start: number, count: number, instances: number): void; - clone(): InstancedBufferGeometry; - copy(source: InstancedBufferGeometry): InstancedBufferGeometry; } /** @@ -1378,11 +1366,11 @@ declare namespace THREE { needsUpdate: boolean; setDynamic(dynamic: boolean): InterleavedBuffer; - clone(): InterleavedBuffer; - copy(source: InterleavedBuffer): InterleavedBuffer; + clone(): this; + copy(source: this): this; copyAt(index1: number, attribute: InterleavedBufferAttribute, index2: number): InterleavedBuffer; set(value: ArrayLike, index: number): InterleavedBuffer; - clone(): InterleavedBuffer; + clone(): this; } /** @@ -1392,9 +1380,6 @@ declare namespace THREE { constructor(array: ArrayLike, stride: number, meshPerAttribute?: number); meshPerAttribute: number; - - clone(): InstancedInterleavedBuffer; - copy(source: InstancedInterleavedBuffer): InstancedInterleavedBuffer; } /** @@ -1686,14 +1671,14 @@ declare namespace THREE { toJSON(meta?: { geometries: any, materials: any, textures: any, images: any }): any; - clone(recursive?: boolean): Object3D; + clone(recursive?: boolean): this; /** * * @param object * @param recursive */ - copy(source: Object3D, recursive?: boolean): Object3D; + copy(source: this, recursive?: boolean): this; // deprecated eulerOrder: string; @@ -1777,9 +1762,6 @@ declare namespace THREE { shadowBias: any; // deprecated, use shadow.bias shadowMapWidth: any; // deprecated, use shadow.mapSize.width shadowMapHeight: any; // deprecated, use shadow.mapSize.height - - copy(source: Light): Light; - clone(recursive?: boolean): Light; } export class LightShadow { @@ -1792,8 +1774,8 @@ declare namespace THREE { map: RenderTarget; matrix: Matrix4; - copy(source: LightShadow): LightShadow; - clone(recursive?: boolean): LightShadow; + copy(source: this): this; + clone(recursive?: boolean): this; toJSON(): any; } @@ -1814,9 +1796,6 @@ declare namespace THREE { constructor(hex?: number|string, intensity?: number); castShadow: boolean; - - copy(source: AmbientLight): AmbientLight; - clone(recursive?: boolean): AmbientLight; } /** @@ -1845,9 +1824,6 @@ declare namespace THREE { intensity: number; shadow: LightShadow; - - copy(source: DirectionalLight): DirectionalLight; - clone(recursive?: boolean): HemisphereLight; } export class DirectionalLightShadow extends LightShadow {} @@ -1857,9 +1833,6 @@ declare namespace THREE { groundColor: Color; intensity: number; - - copy(source: HemisphereLight): HemisphereLight; - clone(recursive?: boolean): HemisphereLight; } /** @@ -1888,9 +1861,6 @@ declare namespace THREE { decay: number; shadow: LightShadow; power: number; - - copy(source: PointLight): PointLight; - clone(recursive?: boolean): PointLight; } /** @@ -1933,9 +1903,6 @@ declare namespace THREE { shadow: SpotLightShadow; power: number; penumbra: number; - - clone(recursive?: boolean): SpotLight; - copy(source: PointLight): SpotLight; } export class SpotLightShadow extends LightShadow { @@ -2359,8 +2326,8 @@ declare namespace THREE { setValues(parameters: MaterialParameters): void; toJSON(meta?: any): any; - clone(): Material; - copy(source: Material): Material; + clone(): this; + copy(source: this): this; update(): void; dispose(): void; @@ -2384,8 +2351,6 @@ declare namespace THREE { linejoin: string; setValues(parameters: LineBasicMaterialParameters): void; - clone(): LineBasicMaterial; - copy(source: LineBasicMaterial): LineBasicMaterial; } export interface LineDashedMaterialParameters extends MaterialParameters { @@ -2406,8 +2371,6 @@ declare namespace THREE { gapSize: number; setValues(parameters: LineDashedMaterialParameters): void; - clone(): LineDashedMaterial; - copy(source: LineDashedMaterial): LineDashedMaterial; } /** @@ -2456,8 +2419,6 @@ declare namespace THREE { morphTargets: boolean; setValues(parameters: MeshBasicMaterialParameters): void; - clone(): MeshBasicMaterial; - copy(source: MeshBasicMaterial): MeshBasicMaterial; } export interface MeshDepthMaterialParameters extends MaterialParameters { @@ -2472,8 +2433,6 @@ declare namespace THREE { wireframeLinewidth: number; setValues(parameters: MeshDepthMaterialParameters): void; - clone(): MeshDepthMaterial; - copy(source: MeshDepthMaterial): MeshDepthMaterial; } export interface MeshLambertMaterialParameters extends MaterialParameters { @@ -2528,8 +2487,6 @@ declare namespace THREE { morphNormals: boolean; setValues(parameters: MeshLambertMaterialParameters): void; - clone(): MeshLambertMaterial; - copy(source: MeshLambertMaterial): MeshLambertMaterial; } export interface MeshStandardMaterialParameters extends MaterialParameters { @@ -2599,8 +2556,6 @@ declare namespace THREE { morphNormals: boolean; setValues(parameters: MeshStandardMaterialParameters): void; - clone(): MeshStandardMaterial; - copy(source: MeshStandardMaterial): MeshStandardMaterial; } export interface MeshNormalMaterialParameters extends MaterialParameters { @@ -2619,8 +2574,6 @@ declare namespace THREE { morphTargets: boolean; setValues(parameters: MeshNormalMaterialParameters): void; - clone(): MeshNormalMaterial; - copy(source: MeshNormalMaterial): MeshNormalMaterial; } export interface MeshPhongMaterialParameters extends MaterialParameters { @@ -2696,8 +2649,6 @@ declare namespace THREE { metal: boolean; // deprecated setValues(parameters: MeshPhongMaterialParameters): void; - clone(): MeshPhongMaterial; - copy(source: MeshPhongMaterial): MeshPhongMaterial; } export interface MeshPhysicalMaterialParameters extends MeshStandardMaterialParameters { @@ -2723,7 +2674,6 @@ declare namespace THREE { materials: Material[]; toJSON(meta: any): any; - clone(): MultiMaterial; } export class MeshFaceMaterial extends MultiMaterial {} // deprecated, use MultiMaterial @@ -2744,8 +2694,6 @@ declare namespace THREE { sizeAttenuation: boolean; setValues(parameters: PointsMaterialParameters): void; - clone(): PointsMaterial; - copy(source: PointsMaterial): PointsMaterial; } export class PointCloudMaterial extends PointsMaterial {} // deprecated @@ -2788,8 +2736,6 @@ declare namespace THREE { index0AttributeName: string; setValues(parameters: ShaderMaterialParameters): void; - clone(): ShaderMaterial; - copy(source: ShaderMaterial): ShaderMaterial; toJSON(meta: any): any; } @@ -2811,8 +2757,6 @@ declare namespace THREE { rotation: number; setValues(parameters: SpriteMaterialParameters): void; - clone(): SpriteMaterial; - copy(source: SpriteMaterial): SpriteMaterial; } export class ShadowMaterial extends ShaderMaterial { @@ -2830,8 +2774,8 @@ declare namespace THREE { set(min: Vector2, max: Vector2): Box2; setFromPoints(points: Vector2[]): Box2; setFromCenterAndSize(center: Vector2, size: Vector2): Box2; - clone(): Box2; - copy(box: Box2): Box2; + clone(): this; + copy(box: this): this; makeEmpty(): Box2; isEmpty(): boolean; center(optionalTarget?: Vector2): Vector2; @@ -2865,8 +2809,8 @@ declare namespace THREE { setFromPoints(points: Vector3[]): Box3; setFromCenterAndSize(center: Vector3, size: Vector3): Box3; setFromObject(object: Object3D): Box3; - clone(): Box3; - copy(box: Box3): Box3; + clone(): this; + copy(box: this): this; makeEmpty(): Box3; isEmpty(): boolean; center(optionalTarget?: Vector3): Vector3; @@ -2962,13 +2906,13 @@ declare namespace THREE { /** * Clones this color. */ - clone(): Color; + clone(): this; /** * Copies given color. * @param color Color to copy. */ - copy(color: Color): Color; + copy(color: this): this; /** * Copies given color making conversion from gamma to linear space. @@ -3184,8 +3128,8 @@ declare namespace THREE { onChangeCallback: Function; set(x: number, y: number, z: number, order?: string): Euler; - clone(): Euler; - copy(euler: Euler): Euler; + clone(): this; + copy(euler: this): this; setFromRotationMatrix(m: Matrix4, order?: string, update?: boolean): Euler; setFromQuaternion(q: Quaternion, order?: string, update?: boolean): Euler; setFromVector3( v: Vector3, order?: string ): Euler; @@ -3212,8 +3156,8 @@ declare namespace THREE { planes: Plane[]; set(p0?: number, p1?: number, p2?: number, p3?: number, p4?: number, p5?: number): Frustum; - clone(): Frustum; - copy(frustum: Frustum): Frustum; + clone(): this; + copy(frustum: this): this; setFromMatrix(m: Matrix4): Frustum; intersectsObject(object: Object3D): boolean; intersectsObject(sprite: Sprite): boolean; @@ -3229,8 +3173,8 @@ declare namespace THREE { end: Vector3; set(start?: Vector3, end?: Vector3): Line3; - clone(): Line3; - copy(line: Line3): Line3; + clone(): this; + copy(line: this): this; center(optionalTarget?: Vector3): Vector3; delta(optionalTarget?: Vector3): Vector3; distanceSq(): number; @@ -3326,7 +3270,7 @@ declare namespace THREE { /** * copy(m:T):T; */ - copy(m: Matrix): Matrix; + copy(m: this): this; /** * multiplyScalar(s:number):T; @@ -3348,7 +3292,7 @@ declare namespace THREE { /** * clone():T; */ - clone(): Matrix; + clone(): this; } /** @@ -3367,8 +3311,8 @@ declare namespace THREE { set(n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number): Matrix3; identity(): Matrix3; - clone(): Matrix3; - copy(m: Matrix3): Matrix3; + clone(): this; + copy(m: this): this; setFromMatrix4(m: Matrix4): Matrix3; applyToVector3Array(array: ArrayLike, offset?: number, length?: number): ArrayLike; applyToBuffer(buffer: BufferAttribute, offset?: number, length?: number): BufferAttribute; @@ -3431,8 +3375,8 @@ declare namespace THREE { * Resets this matrix to identity. */ identity(): Matrix4; - clone(): Matrix4; - copy(m: Matrix4): Matrix4; + clone(): this; + copy(m: this): this; copyPosition(m: Matrix4): Matrix4; extractBasis( xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): Matrix4; makeBasis( xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): Matrix4; @@ -3593,8 +3537,8 @@ declare namespace THREE { setComponents(x: number, y: number, z: number, w: number): Plane; setFromNormalAndCoplanarPoint(normal: Vector3, point: Vector3): Plane; setFromCoplanarPoints(a: Vector3, b: Vector3, c: Vector3): Plane; - clone(): Plane; - copy(plane: Plane): Plane; + clone(): this; + copy(plane: this): this; normalize(): Plane; negate(): Plane; distanceToPoint(point: Vector3): number; @@ -3617,8 +3561,8 @@ declare namespace THREE { constructor(radius?: number, phi?: number, theta?: number); set(radius: number, phi: number, theta: number): Spherical; - clone(): Spherical; - copy(other: Spherical): Spherical; + clone(): this; + copy(other: this): this; makeSafe(): void; setFromVector3(vec3: Vector3): Spherical; } @@ -3654,12 +3598,12 @@ declare namespace THREE { /** * Clones this quaternion. */ - clone(): Quaternion; + clone(): this; /** * Copies values of q to this quaternion. */ - copy(q: Quaternion): Quaternion; + copy(q: this): this; /** * Sets this quaternion from rotation specified by Euler angles. @@ -3739,8 +3683,8 @@ declare namespace THREE { direction: Vector3; set(origin: Vector3, direction: Vector3): Ray; - clone(): Ray; - copy(ray: Ray): Ray; + clone(): this; + copy(ray: this): this; at(t: number, optionalTarget?: Vector3): Vector3; lookAt(v: Vector3): Vector3; recast(t: number): Ray; @@ -3773,8 +3717,8 @@ declare namespace THREE { set(center: Vector3, radius: number): Sphere; setFromPoints(points: Vector3[], optionalCenter?: Vector3): Sphere; - clone(): Sphere; - copy(sphere: Sphere): Sphere; + clone(): this; + copy(sphere: this): this; empty(): boolean; containsPoint(point: Vector3): boolean; distanceToPoint(point: Vector3): number; @@ -3850,8 +3794,8 @@ declare namespace THREE { set(a: Vector3, b: Vector3, c: Vector3): Triangle; setFromPointsAndIndices(points: Vector3[], i0: number, i1: number, i2: number): Triangle; - clone(): Triangle; - copy(triangle: Triangle): Triangle; + clone(): this; + copy(triangle: this): this; area(): number; midpoint(optionalTarget?: Vector3): Vector3; normal(optionalTarget?: Vector3): Vector3; @@ -3885,7 +3829,7 @@ declare namespace THREE { /** * copy(v:T):T; */ - copy(v: Vector): Vector; + copy(v: this): this; /** * add(v:T):T; @@ -3974,7 +3918,7 @@ declare namespace THREE { /** * clone():T; */ - clone(): Vector; + clone(): this; } /** @@ -4019,11 +3963,11 @@ declare namespace THREE { /** * Clones this vector. */ - clone(): Vector2; + clone(): this; /** * Copies value of v to this vector. */ - copy(v: Vector2): Vector2; + copy(v: this): this; /** * Adds v to this vector. @@ -4185,11 +4129,11 @@ declare namespace THREE { /** * Clones this vector. */ - clone(): Vector3; + clone(): this; /** * Copies value of v to this vector. */ - copy(v: Vector3): Vector3; + copy(v: this): this; /** * Adds v to this vector. @@ -4381,11 +4325,11 @@ declare namespace THREE { /** * Clones this vector. */ - clone(): Vector4; + clone(): this; /** * Copies value of v to this vector. */ - copy(v: Vector4): Vector4; + copy(v: this): this; /** * Adds v to this vector. @@ -4533,9 +4477,6 @@ declare namespace THREE { constructor(skin: SkinnedMesh); skin: SkinnedMesh; - - clone(): Bone; - copy(source: Bone): Bone; } export class Group extends Object3D { @@ -4551,8 +4492,6 @@ declare namespace THREE { getObjectForDistance(distance: number): Object3D; raycast(raycaster: Raycaster, intersects: any): void; update(camera: Camera): void; - clone(): LOD; - copy(source: LOD): LOD; toJSON(meta: any): any; // deprecated @@ -4583,8 +4522,6 @@ declare namespace THREE { add(object: Object3D): void; add(texture: Texture, size?: number, distance?: number, blending?: Blending, color?: Color): void; updateLensFlares(): void; - clone(): LensFlare; - copy(source: LensFlare): LensFlare; } export class Line extends Object3D { @@ -4598,8 +4535,6 @@ declare namespace THREE { material: Material; // LineDashedMaterial or LineBasicMaterial or ShaderMaterial raycast(raycaster: Raycaster, intersects: any): void; - clone(): Line; - copy(source: Line): Line; } export const LineStrip: number; // deprecated @@ -4611,9 +4546,6 @@ declare namespace THREE { material?: LineDashedMaterial | LineBasicMaterial | ShaderMaterial, mode?: number ); - - clone(): LineSegments; - copy(source: LineSegments): LineSegments; } enum LineMode {} @@ -4630,8 +4562,6 @@ declare namespace THREE { updateMorphTargets(): void; getMorphTargetIndexByName(name: string): number; raycast(raycaster: Raycaster, intersects: any): void; - clone(): Mesh; - copy(source: Mesh): Mesh; } /** @@ -4661,8 +4591,6 @@ declare namespace THREE { material: Material; raycast(raycaster: Raycaster, intersects: any): void; - clone(): Points; - copy(source: Points): Points; } export class PointCloud extends Points {} // deprecated @@ -4683,7 +4611,7 @@ declare namespace THREE { calculateInverses(bone: Bone): void; pose(): void; update(): void; - clone(): Skeleton; + clone(): this; } export class SkinnedMesh extends Mesh { @@ -4704,8 +4632,6 @@ declare namespace THREE { pose(): void; normalizeSkinWeights(): void; updateMatrixWorld(force?: boolean): void; - clone(): SkinnedMesh; - copy(source: SkinnedMesh): SkinnedMesh; } export class Sprite extends Object3D { @@ -4715,8 +4641,6 @@ declare namespace THREE { material: SpriteMaterial; raycast(raycaster: Raycaster, intersects: any): void; - clone(): Sprite; - copy(source: Sprite): Sprite; } export class Particle extends Sprite {} // deprecated @@ -5048,8 +4972,8 @@ declare namespace THREE { generateMipmaps: any; // deprecated, use texture.generateMipmaps setSize(width: number, height: number): void; - clone(): WebGLRenderTarget; - copy(source: WebGLRenderTarget): WebGLRenderTarget; + clone(): this; + copy(source: this): this; dispose(): void; } @@ -5596,14 +5520,13 @@ declare namespace THREE { autoUpdate: boolean; background: any; - copy(source: Scene, recursive?: boolean): Scene; toJSON(meta?: any): any; } export interface IFog { name: string; color: Color; - clone(): IFog; + clone(): this; toJSON(): any; } @@ -5631,7 +5554,7 @@ declare namespace THREE { */ far: number; - clone(): Fog; + clone(): this; toJSON(): any; } @@ -5650,7 +5573,7 @@ declare namespace THREE { */ density: number; - clone(): FogExp2; + clone(): this; toJSON(): any; } @@ -5698,8 +5621,8 @@ declare namespace THREE { static DEFAULT_IMAGE: any; static DEFAULT_MAPPING: any; - clone(): Texture; - copy(source: Texture): Texture; + clone(): this; + copy(source: this): this; toJSON(meta: any): any; dispose(): void; transformUv(uv: Vector): void; @@ -5733,9 +5656,6 @@ declare namespace THREE { type?: TextureDataType, anisotropy?: number ); - - clone(): CanvasTexture; - copy(source: CanvasTexture): CanvasTexture; } export class CubeTexture extends Texture { @@ -5753,8 +5673,6 @@ declare namespace THREE { ); images: any; // returns and sets the value of Texture.image in the codde ? - - copy(source: CubeTexture): CubeTexture; } export class CompressedTexture extends Texture { @@ -5774,9 +5692,6 @@ declare namespace THREE { ); image: { width: number; height: number; }; - - clone(): CompressedTexture; - copy(source: CompressedTexture): CompressedTexture; } export class DataTexture extends Texture { @@ -5796,9 +5711,6 @@ declare namespace THREE { ); image: { data: ImageData; width: number; height: number; }; - - clone(): DataTexture; - copy(source: DataTexture): DataTexture; } export class VideoTexture extends Texture { @@ -5813,9 +5725,6 @@ declare namespace THREE { type?: TextureDataType, anisotropy?: number ); - - clone(): VideoTexture; - copy(source: VideoTexture): VideoTexture; } // Extras ///////////////////////////////////////////////////////////////////// @@ -6221,8 +6130,6 @@ declare namespace THREE { heightSegments: number; depthSegments: number; }; - - clone(): BoxGeometry; } export class CubeGeometry extends BoxGeometry {} // deprecated, use BoxGeometry @@ -6306,8 +6213,6 @@ declare namespace THREE { export class EdgesGeometry extends BufferGeometry { constructor(geometry: BufferGeometry, thresholdAngle: number); - - clone(): EdgesGeometry; } export class ExtrudeGeometry extends Geometry { From 7c9f3114a756f052ca10caba615540d7b5eb19be Mon Sep 17 00:00:00 2001 From: Dave Dunkin Date: Fri, 16 Sep 2016 12:10:31 -0700 Subject: [PATCH 524/844] Fix elasticsearch get, mget, msearch responses. (#11259) * Fix elasticsearch get, mget, msearch responses. * Fix contributor github links. --- elasticsearch/elasticsearch.d.ts | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index e2079b19d0..d983817869 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -1,6 +1,6 @@ // Type definitions for elasticsearch // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt , Blake Smith +// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module Elasticsearch { @@ -15,14 +15,14 @@ declare module Elasticsearch { 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; @@ -196,7 +196,8 @@ declare module Elasticsearch { versionType?: string; } - export interface GetResponse extends GenericParams { + export interface GetResponse { + _index: string; _type: string; _id: string; _version: number; @@ -279,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; @@ -290,6 +295,10 @@ declare module Elasticsearch { type?: string; } + export interface MGetResponse { + docs?: GetResponse[]; + } + export interface IndicesIndexExitsParams extends GenericParams { index: string | string[] | boolean; ignoreUnavailable?: boolean; From e0a4b59de6eea0e2c70b0a403a6566d402f0e1d3 Mon Sep 17 00:00:00 2001 From: Julien Sergent Date: Sat, 17 Sep 2016 00:05:58 +0200 Subject: [PATCH 525/844] Update facebook-js-sdk.d.ts --- facebook-js-sdk/facebook-js-sdk.d.ts | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) 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 { From bb69a3320f934d39d1ce65a024b9b3464283fe02 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Sat, 17 Sep 2016 13:28:12 +0800 Subject: [PATCH 526/844] Delete pug-test.ts --- pug/pug-test.ts | 103 ------------------------------------------------ 1 file changed, 103 deletions(-) delete mode 100644 pug/pug-test.ts diff --git a/pug/pug-test.ts b/pug/pug-test.ts deleted file mode 100644 index 5ba7d9ad06..0000000000 --- a/pug/pug-test.ts +++ /dev/null @@ -1,103 +0,0 @@ -/// -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; - }); - } -} From 9d4d9924f1a5562c61421d82d8f4f474a425fb04 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 14:10:19 +0800 Subject: [PATCH 527/844] [node] Clean up tls_tests and wrap in namespace (#11248) * Clean up tls_tests and wrap in namespace for v6.x * Clean up tls_tests and wrap in namespace for v4.x --- node/node-4-tests.ts | 28 +++++++++++++++------------- node/node-tests.ts | 28 +++++++++++++++------------- 2 files changed, 30 insertions(+), 26 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 2de910db67..66fc18ce24 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -369,21 +369,23 @@ namespace crypto_tests { } } -//////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////// +/// TLS tests : http://nodejs.org/api/tls.html /// +////////////////////////////////////////////////// -var ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", -}); -var blah = ctx.context; +namespace tls_tests { + 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); + var connOpts: tls.ConnectionOptions = { + host: "127.0.0.1", + port: 55 + }; + var tlsSocket = tls.connect(connOpts); +} //////////////////////////////////////////////////// /// Http tests : http://nodejs.org/api/http.html /// diff --git a/node/node-tests.ts b/node/node-tests.ts index e0600d936d..06fb4a9bf7 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -544,21 +544,23 @@ namespace crypto_tests { } } -//////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////// +/// TLS tests : http://nodejs.org/api/tls.html /// +////////////////////////////////////////////////// -var ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", -}); -var blah = ctx.context; +namespace tls_tests { + 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); + var connOpts: tls.ConnectionOptions = { + host: "127.0.0.1", + port: 55 + }; + var tlsSocket = tls.connect(connOpts); +} //////////////////////////////////////////////////// /// Http tests : http://nodejs.org/api/http.html /// From 3e403832f65f64c1ad1b2e29e4e520838519e14b Mon Sep 17 00:00:00 2001 From: Tommy Frazier Date: Mon, 19 Sep 2016 02:10:41 -0400 Subject: [PATCH 528/844] Add httpsServerOptions to ServerOptions interface (#11155) --- restify/restify.d.ts | 1 + 1 file changed, 1 insertion(+) 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 { From 5e55876028163634704f9f73db4fce2314e02a7d Mon Sep 17 00:00:00 2001 From: Constantin Date: Mon, 19 Sep 2016 08:11:16 +0200 Subject: [PATCH 529/844] webix - added fail to Promise (#11250) --- webix/webix.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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; From 863fdd02c68c82696163f06d8d5b8ce40a10f64d Mon Sep 17 00:00:00 2001 From: Natan Vivo Date: Mon, 19 Sep 2016 03:13:38 -0300 Subject: [PATCH 530/844] Added component option to angular ui bootstrap modal settings. (#11249) --- angular-ui-bootstrap/angular-ui-bootstrap.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index dd129d141d..1d0e28b859 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -329,6 +329,12 @@ declare namespace angular.ui.bootstrap { * @default false */ bindToController?: boolean; + + /** + * 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. + */ + component?: string; /** * members that will be resolved and passed to the controller as locals; it is equivalent of the `resolve` property for AngularJS routes From e69548d34035dbb8dfb11162c6e1b2df0a894a79 Mon Sep 17 00:00:00 2001 From: Martin D Date: Mon, 19 Sep 2016 02:15:00 -0400 Subject: [PATCH 531/844] Fixed arguments for tooltips value formatting (#11253) * Update c3.d.ts Fixed arguments for tooltips value formatting * Update c3.d.ts --- c3/c3.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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. From 83adc941d134189c3a55afb73e940ce70308b35b Mon Sep 17 00:00:00 2001 From: Zipeng WU Date: Mon, 19 Sep 2016 08:15:16 +0200 Subject: [PATCH 532/844] Support syncBrushing option on Focus component (#11204) --- nvd3/nvd3.d.ts | 2 ++ 1 file changed, 2 insertions(+) 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 { From c0ce167c104f2224111c87fb81c8be5c530916ba Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 02:15:35 -0400 Subject: [PATCH 533/844] Improve polylabel ES6 import syntax (#11260) Using `import * as polylabel from 'polylabel'` is now valid in Typescript vs. require('polylabel'). --- polylabel/polylabel-tests.ts | 12 +++++------- polylabel/polylabel.d.ts | 5 +++-- 2 files changed, 8 insertions(+), 9 deletions(-) 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; } From 50155318b25a75908cb1427ac8b1ab7a9108949c Mon Sep 17 00:00:00 2001 From: Nick Graef Date: Mon, 19 Sep 2016 01:16:16 -0500 Subject: [PATCH 534/844] fix function signatures (#11261) Documentation: https://github.com/mgonto/restangular#restangular-methods According to the documentation and source code, `all` and `allUrl` return collections, not elements. Additionally, the `post` signature without `subElement` is only available on collections, not elements. --- restangular/restangular.d.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) 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; From 609f1f78e8e830c46cb3ac6876102c62d274821f Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 02:17:07 -0400 Subject: [PATCH 535/844] Implement concaveman definition (#11262) * Implement concaveman definition Author of concaveman module @mourner * remove console log --- concaveman/concaveman-tests.ts | 5 +++++ concaveman/concaveman.d.ts | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 concaveman/concaveman-tests.ts create mode 100644 concaveman/concaveman.d.ts 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; +} From 8a8a1396214462baab5b04c498d3b2d869d4c5ed Mon Sep 17 00:00:00 2001 From: Alexander Kalitenya Date: Mon, 19 Sep 2016 11:17:38 +0500 Subject: [PATCH 536/844] Update auth0.lock.d.ts (#11199) --- auth0.lock/auth0.lock.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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}; From 18d656dda34aae2e331ab2c462c6aa328fbd387e Mon Sep 17 00:00:00 2001 From: ersimont Date: Mon, 19 Sep 2016 02:19:25 -0400 Subject: [PATCH 537/844] Update angular-ui-bootstrap.d.ts (#11263) Add `component` option for modals --- angular-ui-bootstrap/angular-ui-bootstrap.d.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index 1d0e28b859..71ef8b7363 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -406,6 +406,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 { From b0a9f0e1dbf998308a54f7738b8779f83f00c3fc Mon Sep 17 00:00:00 2001 From: Endel Dreyer Date: Mon, 19 Sep 2016 08:24:20 +0200 Subject: [PATCH 538/844] Add totalFrames and duration properties to MovieClip (#11270) Official documentation for those properties: - http://www.createjs.com/docs/easeljs/classes/MovieClip.html#property_totalFrames - http://www.createjs.com/docs/easeljs/classes/MovieClip.html#property_duration --- easeljs/easeljs.d.ts | 2 ++ 1 file changed, 2 insertions(+) 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 From 48649b87187b5ff3448d291c847a35da65d12d93 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 14:29:20 +0800 Subject: [PATCH 539/844] [node] Add events and exitedAfterDisconnect in cluster.work (#11275) * Add events for cluster.worker * Add exitedAfterDisconnect for cluster.Worker --- node/node.d.ts | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/node/node.d.ts b/node/node.d.ts index 81b13e4e1d..54e826301a 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -778,6 +778,56 @@ 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 interface Cluster extends events.EventEmitter { From 28d94377786d6da325b76614aa4c1849dc05703e Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 14:30:32 +0800 Subject: [PATCH 540/844] Add events for fs (#11277) --- node/node.d.ts | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/node/node.d.ts b/node/node.d.ts index 54e826301a..888da5cec4 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1788,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; } /** From 93d269d6da3a675d49648330b412a6c7b6981c89 Mon Sep 17 00:00:00 2001 From: "Dmitry A. Efimenko" Date: Sun, 18 Sep 2016 23:49:21 -0700 Subject: [PATCH 541/844] added prop options and func timeFormatter (#11256) added property `options`, which can be found in [the code](https://github.com/joewalnes/smoothie/blob/15fc4b62f5b23c8d5dd1784c820ae73f341626e6/smoothie.js#L270). Even though it's not mentioned in the docs, it useful to be able to access these options after chart is initialized when you want to change appearance in real tme. added function `timeFormatter`, which is mentioned in [right here, in the definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/smoothie/smoothie.d.ts#L127) and can be found in [the code](https://github.com/joewalnes/smoothie/blob/15fc4b62f5b23c8d5dd1784c820ae73f341626e6/smoothie.js#L795) --- smoothie/smoothie.d.ts | 4 ++++ 1 file changed, 4 insertions(+) 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; } } From 80e5c9b45b7ddd6442bcabbebf418fa1a658307b Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 02:50:52 -0400 Subject: [PATCH 542/844] Define Turf 3.5.2 definition (#11123) * Define Turf 3.5.2 definition 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 - [ ] inside - [ ] tag GRIDS - [ ] hexGrid - [ ] pointGrid - [ ] squareGrid - [ ] triangleGrid - [ ] within CLASSIFICATION - [ ] nearest META - [ ] propEach - [ ] coordEach - [ ] coordReduce - [ ] featureEach - [ ] getCoord ASSERTIONS - [ ] featureOf - [ ] collectionOf - [ ] bbox - [ ] circle - [ ] geojsonType - [ ] propReduce - [ ] coordAll - [ ] tesselate * Added Turf Grids functions - Added more variables to data initialisation. - Remove excess feature points. - Add URL in `@name` in function JSDocs GRIDS - [x] hexGrid - [x] pointGrid - [x] squareGrid - [x] triangleGrid * Use the latest Turf import - Added in test case how to import individal functions npm install in Node.js ``` npm install @turf/turf ``` https://github.com/Turfjs/turf * Change Turf functions into interfaces * Added Turf typeof units `units` is an optional parameter for all Turf functions with the following options `'miles' | 'nauticalmiles' | 'degrees' | 'radians' | 'inches' | 'yards' | 'meters' | 'metres' | 'kilometers' | 'kilometres'` * Update Turf `inside` & `tag` Add JSDocs & validate both methods * Add imports to Turf submodules * Add Author to Turf @vvakame followed the same syntax as Lodash * Simplify Turf `intersect` interface Turf only officially supports `poly,poly`, all other geometry input/outputs are valid, however can't control the outputs. https://github.com/Turfjs/turf/pull/479 * Comment Turf export default module Next release of Turf will have this implemented * Remove default export turf Was meant to be a comment instead, removed it for now to be safe, it will become available next release * Added Turf.bbox function --- turf/turf-2.0-tests.ts | 522 +++++++++++++++++ turf/turf-2.0.d.ts | 580 +++++++++++++++++++ turf/turf-tests.ts | 512 +++++++++-------- turf/turf.d.ts | 1203 ++++++++++++++++++++++++++++++---------- 4 files changed, 2265 insertions(+), 552 deletions(-) create mode 100644 turf/turf-2.0-tests.ts create mode 100644 turf/turf-2.0.d.ts 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; +// } From ee9a6159396bdfde7d345df6e6b5cdf57fdb9bcc Mon Sep 17 00:00:00 2001 From: Borislav Zhivkov Date: Mon, 19 Sep 2016 09:51:04 +0300 Subject: [PATCH 543/844] Add angular-feature-flags definitions (#11283) --- .../angular-feature-flags-tests.ts | 31 +++++++++++++++ .../angular-feature-flags.d.ts | 38 +++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 angular-feature-flags/angular-feature-flags-tests.ts create mode 100644 angular-feature-flags/angular-feature-flags.d.ts 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 From 4b8264149240480dec8d6d6b2dd97ddaedba4142 Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Sun, 18 Sep 2016 23:56:50 -0700 Subject: [PATCH 544/844] Update to Electron 1.3.6 (#11229) --- github-electron/github-electron.d.ts | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 3dc72d7075..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.5 +// 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. * @@ -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. @@ -1367,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. @@ -1957,7 +1967,7 @@ declare namespace Electron { interface CrashReporterStartOptions { /** - * Default: Electron + * Default: app.getName() */ productName?: string; companyName: string; @@ -3392,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?: { /** @@ -3412,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; /** From 1adaa22d7a6cc83ce09638e2cae00fc6f6589857 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20S=C3=A1nchez?= Date: Mon, 19 Sep 2016 01:07:25 -0600 Subject: [PATCH 545/844] [WIP] Add type definitions for Leaflet 1.0 (#11165) * Rename leaflet.d.ts to leaflet-0.7.d.ts * Defined several important interfaces and the skeleton of some others * Started adding tests * Added more interfaces, factory methods and tests * Implemented other interfaces and nested namespaces * Added more types --- heatmap.js/heatmap.d.ts | 2 +- leaflet-curve/leaflet-curve-tests.ts | 2 +- leaflet-curve/leaflet-curve.d.ts | 2 +- leaflet-draw/leaflet-draw-tests.ts | 4 +- leaflet-draw/leaflet-draw.d.ts | 2 +- leaflet-editable/leaflet-editable.d.ts | 2 +- .../leaflet-geocoder-mapzen-tests.ts | 2 +- .../leaflet-geocoder-mapzen.d.ts | 2 +- leaflet-label/leaflet-label.d.ts | 2 +- .../leaflet-markercluster.d.ts | 8 +- .../leaflet.awesome-markers.d.ts | 2 +- leaflet.fullscreen/leaflet.fullscreen.d.ts | 2 +- leaflet/leaflet-0.7-tests.ts | 427 ++ leaflet/leaflet-0.7.d.ts | 4382 ++++++++++++++ leaflet/leaflet-tests.ts | 690 +-- leaflet/leaflet.d.ts | 5095 +++-------------- mapbox/mapbox.d.ts | 2 +- 17 files changed, 5911 insertions(+), 4717 deletions(-) create mode 100644 leaflet/leaflet-0.7-tests.ts create mode 100644 leaflet/leaflet-0.7.d.ts 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/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 ///////////////////////////// From 549f6a3fa9c51e15d9c0529d1e0b9ca3cf059376 Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Mon, 19 Sep 2016 10:09:32 +0300 Subject: [PATCH 546/844] Add svgIcon to MuiTheme (#11293) https://github.com/callemall/material-ui/blob/master/src/styles/getMuiTheme.js#L249-L251 --- material-ui/material-ui.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index 2430923d9d..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; }; From cf6fef6e8a8d68211e6d05196c658926c213e3b8 Mon Sep 17 00:00:00 2001 From: iskandersierra Date: Mon, 19 Sep 2016 09:14:34 +0200 Subject: [PATCH 547/844] Added typings for change-emitter@0.1.2 (#11295) --- change-emitter/change-emitter-tests.ts | 124 +++++++++++++++++++++++++ change-emitter/change-emitter.d.ts | 58 ++++++++++++ 2 files changed, 182 insertions(+) create mode 100644 change-emitter/change-emitter-tests.ts create mode 100644 change-emitter/change-emitter.d.ts 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; +} From e0e86e35352adab42fe829936c199863a6e28d27 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 15:16:55 +0800 Subject: [PATCH 548/844] [express] http.createServer can take express app (#11292) * Create pug-test.ts * Test http.createServer can take express app * Delete this --- express/express-tests.ts | 179 +++++++++++++++++++++------------------ 1 file changed, 96 insertions(+), 83 deletions(-) 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); + } +} From 6fbe7a4242ee73c416397e7d54c85f2eab0058ce Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 03:18:09 -0400 Subject: [PATCH 549/844] Implemented Proj4 definition (#11303) * Implement Proj4 definition * Add proj4 tests --- proj4/proj4-tests.ts | 50 +++++++++++++++++++ proj4/proj4.d.ts | 116 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 166 insertions(+) create mode 100644 proj4/proj4-tests.ts create mode 100644 proj4/proj4.d.ts 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 +} From 4fd81af1e812fc860fd7acc844f9fac5247372e6 Mon Sep 17 00:00:00 2001 From: Jay Anslow Date: Mon, 19 Sep 2016 08:18:23 +0100 Subject: [PATCH 550/844] Use bluebird@3 instead of @2 (#11299) --- fs-extra-promise/fs-extra-promise.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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"); From 1ce244c131e77a19c72952cab39e7deba645f6df Mon Sep 17 00:00:00 2001 From: Mitchell Wills Date: Mon, 19 Sep 2016 00:19:32 -0700 Subject: [PATCH 551/844] Correct the Angular Material IToastService updateContent typings (#11305) --- angular-material/angular-material-tests.ts | 5 ++++- angular-material/angular-material.d.ts | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) 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; } From 4c7b1220e0266d0f7eae7b78ecfbb0823e1d9315 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 03:22:08 -0400 Subject: [PATCH 552/844] Implemented shapefile definition (#11307) * Implement shapefile definition * Implement shapefile definition * Shapefile remove Promise reference --- shapefile/shapefile-tests.ts | 19 +++++++++++++++++++ shapefile/shapefile.d.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 shapefile/shapefile-tests.ts create mode 100644 shapefile/shapefile.d.ts 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 +} From b36bf17397d104c12df35f44b75cda262946b140 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 15:23:24 +0800 Subject: [PATCH 553/844] [pug] Create pug definition (#11258) * Create pug.d.ts * Create pug-test.ts * Add project in comments * Rename --- pug/pug-tests.ts | 103 +++++++++++++++++++++++++++++++++++++++++++++++ pug/pug.d.ts | 50 +++++++++++++++++++++++ 2 files changed, 153 insertions(+) create mode 100644 pug/pug-tests.ts create mode 100644 pug/pug.d.ts 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; +} From 150546f73b24ed9569e22f88a28fcbaf7be51402 Mon Sep 17 00:00:00 2001 From: doronbrikman Date: Mon, 19 Sep 2016 10:23:35 +0300 Subject: [PATCH 554/844] Update enzyme.d.ts (#11252) add render method to ReactWrapper --- enzyme/enzyme.d.ts | 1 + 1 file changed, 1 insertion(+) 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. From 012b7f1072c1e9bd5d0b309b4d194a014a02ed5f Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 15:24:01 +0800 Subject: [PATCH 555/844] [node] Format test definition (#11308) * Format test definition in v4.x * Format test definition in v6.x --- node/node-4-tests.ts | 108 ++++++++++++------------ node/node-tests.ts | 192 +++++++++++++++++++++---------------------- 2 files changed, 150 insertions(+), 150 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 66fc18ce24..26e201c910 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -28,36 +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"); - + assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); - + assert.doesNotThrow(() => { const b = false; if (b) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); - + assert.equal(3, "3", "uses == comparator"); assert.fail(1, 2, undefined, '>'); - + assert.ifError(0); - + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - + assert.notEqual(1, 2, "uses != comparator"); - + assert.notStrictEqual(2, "2", "uses === comparator"); - + assert.ok(true); assert.ok(1); - - assert.strictEqual(1, 1, "uses === comparator"); - + + assert.strictEqual(1, 1, "uses === comparator"); + assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); } } @@ -108,7 +108,7 @@ namespace events_tests { result = emitter.emit(event, any, any); result = emitter.emit(event, any, any, any); } - + { class Networker extends events.EventEmitter { constructor() { @@ -145,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); } { @@ -183,7 +183,7 @@ namespace fs_tests { 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); @@ -197,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]]) @@ -262,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); } } @@ -275,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" } - }); + }); } { @@ -299,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 }); } } @@ -324,17 +324,17 @@ namespace crypto_tests { { var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); } - + { let hmac: crypto.Hmac; (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { let hash: Buffer | string = hmac.read(); }); } - + { //crypto_cipher_decipher_string_test - let key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let 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"); @@ -399,26 +399,26 @@ namespace http_tests { } { - 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() { }); @@ -487,7 +487,7 @@ namespace dgram_tests { //////////////////////////////////////////////////// namespace querystring_tests { - type SampleObject = {a: string; b: number;} + type SampleObject = { a: string; b: number; } { let obj: SampleObject; @@ -540,7 +540,7 @@ namespace path_tests { try { path.join('foo', {}, 'bar'); } - catch(error) { + catch (error) { } @@ -654,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' @@ -724,7 +724,7 @@ namespace readline_tests { } { - let data: string|Buffer; + let data: string | Buffer; let key: readline.Key; rl.write(data); @@ -741,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); } @@ -780,7 +780,7 @@ namespace string_decoder_tests { namespace child_process_tests { { childProcess.exec("echo test"); - childProcess.spawnSync("echo test"); + childProcess.spawnSync("echo test"); } } @@ -788,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 => { @@ -840,7 +840,7 @@ namespace os_tests { } { - let result: {[index: string]: os.NetworkInterfaceInfo[]}; + let result: { [index: string]: os.NetworkInterfaceInfo[] }; result = os.networkInterfaces(); } @@ -918,7 +918,7 @@ namespace process_tests { { var eventEmitter: events.EventEmitter; eventEmitter = process; // Test that process implements EventEmitter... - + var _p: NodeJS.Process = process; _p = p; } diff --git a/node/node-tests.ts b/node/node-tests.ts index 06fb4a9bf7..1fcf149e99 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -30,36 +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"); - + assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); - + assert.doesNotThrow(() => { const b = false; if (b) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); - + assert.equal(3, "3", "uses == comparator"); assert.fail(1, 2, undefined, '>'); - + assert.ifError(0); - + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - + assert.notEqual(1, 2, "uses != comparator"); - + assert.notStrictEqual(2, "2", "uses === comparator"); - + assert.ok(true); assert.ok(1); - - assert.strictEqual(1, 1, "uses === comparator"); - + + assert.strictEqual(1, 1, "uses === comparator"); + assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); } } @@ -118,7 +118,7 @@ namespace events_tests { result = emitter.eventNames(); } - + { class Networker extends events.EventEmitter { constructor() { @@ -139,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) => { @@ -172,52 +172,52 @@ 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); } } @@ -228,7 +228,7 @@ namespace fs_tests { 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); @@ -250,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]]) @@ -373,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); } } @@ -386,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" } - }); + }); } { @@ -410,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 }); } } @@ -430,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(); @@ -449,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(); @@ -467,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(); @@ -499,17 +499,17 @@ namespace crypto_tests { { var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); } - + { let hmac: crypto.Hmac; (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { let hash: Buffer | string = hmac.read(); }); } - + { //crypto_cipher_decipher_string_test - let key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let 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"); @@ -574,26 +574,26 @@ namespace http_tests { } { - 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() { }); @@ -665,7 +665,7 @@ namespace dgram_tests { //////////////////////////////////////////////////// namespace querystring_tests { - type SampleObject = {a: string; b: number;} + type SampleObject = { a: string; b: number; } { let obj: SampleObject; @@ -718,7 +718,7 @@ namespace path_tests { try { path.join('foo', {}, 'bar'); } - catch(error) { + catch (error) { } @@ -832,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' @@ -902,7 +902,7 @@ namespace readline_tests { } { - let data: string|Buffer; + let data: string | Buffer; let key: readline.Key; rl.write(data); @@ -919,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); } @@ -961,7 +961,7 @@ namespace string_decoder_tests { namespace child_process_tests { { childProcess.exec("echo test"); - childProcess.spawnSync("echo test"); + childProcess.spawnSync("echo test"); } } @@ -969,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 => { @@ -1021,7 +1021,7 @@ namespace os_tests { } { - let result: {[index: string]: os.NetworkInterfaceInfo[]}; + let result: { [index: string]: os.NetworkInterfaceInfo[] }; result = os.networkInterfaces(); } @@ -1082,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); @@ -1124,7 +1124,7 @@ namespace process_tests { { var eventEmitter: events.EventEmitter; eventEmitter = process; // Test that process implements EventEmitter... - + var _p: NodeJS.Process = process; _p = p; } From 4f0bb211cf6daaaa8720ca2b598683a6951f81dc Mon Sep 17 00:00:00 2001 From: Julien Sergent Date: Mon, 19 Sep 2016 10:50:50 +0200 Subject: [PATCH 556/844] Update facebook-js-sdk-tests.ts --- facebook-js-sdk/facebook-js-sdk-tests.ts | 6 ++++++ 1 file changed, 6 insertions(+) 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); From a03bb7d3be1f19d9280330297e0456e632c9b71f Mon Sep 17 00:00:00 2001 From: sumit2chauhan Date: Mon, 19 Sep 2016 14:35:01 +0530 Subject: [PATCH 557/844] There is a typescript build error in this The property " component? " in IModalSettings is repeated. --- angular-ui-bootstrap/angular-ui-bootstrap.d.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index 71ef8b7363..d6c389146b 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -329,12 +329,6 @@ declare namespace angular.ui.bootstrap { * @default false */ bindToController?: boolean; - - /** - * 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. - */ - component?: string; /** * members that will be resolved and passed to the controller as locals; it is equivalent of the `resolve` property for AngularJS routes From 26bb1f5bc53e3ba493aa4269f94b9d3db18c32ca Mon Sep 17 00:00:00 2001 From: NoHomey Date: Mon, 19 Sep 2016 17:14:45 +0300 Subject: [PATCH 558/844] Updating jest.d.ts to be close to what @jwbay requested --- jest/jest-tests.ts | 1 + jest/jest.d.ts | 329 ++++++++++++++++++++++++++++++++++++--------- 2 files changed, 268 insertions(+), 62 deletions(-) diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index 04fba5ab09..b547bd40ad 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -1,4 +1,5 @@ /// +/// // Tests based on the Jest website jest.unmock('../sum'); diff --git a/jest/jest.d.ts b/jest/jest.d.ts index 506bd6533d..d0660193f6 100644 --- a/jest/jest.d.ts +++ b/jest/jest.d.ts @@ -1,55 +1,146 @@ // Type definitions for Jest 15.1.1 // Project: http://facebook.github.io/jest/ -// Definitions by: Asana , Ivo Stratev +// Definitions by: Asana , Ivo Stratev , jwbay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +declare var beforeAll: jest.Lifecycle; +declare var beforeEach: jest.Lifecycle; +declare var afterAll: jest.Lifecycle; +declare var afterEach: jest.Lifecycle; +declare var describe: jest.Describe; +declare var fdescribe: jest.Describe; +declare var xdescribe: jest.Describe; +declare var it: jest.It; +declare var fit: jest.It; +declare var xit: jest.It; +declare var test: jest.It; +declare var xtest: jest.It; -declare function afterEach(fn: () => any): void; -declare function beforeEach(fn: () => any): void; -declare function describe(name: string, fn: () => any): void; declare function expect(actual: any): jest.Matchers; -declare function it(name: string, fn: () => any): void; -declare function fit(name: string, fn: () => any): void; -declare function test(name: string, fn: () => any): void; -declare function xdescribe(name: string, fn: () => any): void; -declare function xit(name: string, fn: () => any): void; +interface NodeRequire { + /** Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. */ + requireActual(moduleName: string): any; + /** Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not. */ + requireMock(moduleName: string): any; +} declare namespace jest { - interface Matchers { - lastCalledWith(...args: any[]): boolean; - not: Matchers; - toBe(expected: any): boolean; - toBeCalled(): boolean; - toBeCalledWith(...args: any[]): boolean; - toBeCloseTo(expected: number, delta: number): boolean; - toBeDefined(): boolean; - toBeFalsy(): boolean; - toBeGreaterThan(expected: number): boolean; - toBeGreaterThanOrEqual(expected: number): boolean; - toBeLessThan(expected: number): boolean; - toBeLessThanOrEqual(expected: number): boolean; - toBeNull(): boolean; - toBeTruthy(): boolean; - toBeUndefined(): boolean; - toContain(expected: string): boolean; - toEqual(expected: any): boolean; - toMatch(expected: RegExp): boolean; - toMatchSnapshot(): boolean; - toThrow(): boolean; - toThrowError(expected: string | RegExp): boolean; - toThrowError(expected: TFunction): boolean; - } - - interface MockContext { - calls: any[][]; - instances: T[]; + function addMatchers(matchers: jasmine.CustomMatcherFactories): void; + /** Disables automatic mocking in the module loader. */ + function autoMockOff(): void; + /** Enables automatic mocking in the module loader. */ + function autoMockOn(): void; + /** Removes any pending timers from the timer system. If any timers have been scheduled, they will be cleared and will never have the opportunity to execute in the future. */ + function clearAllTimers(): void; + /** Indicates that the module system should never return a mocked version of the specified module, including all of the specificied module's dependencies. */ + function deepUnmock(moduleName: string): void; + /** Disables automatic mocking in the module loader. */ + function disableAutomock(): void; + /** Mocks a module with an auto-mocked version when it is being required. */ + function doMock(moduleName: string): void; + /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ + function dontMock(moduleName: string): void; + /** Enables automatic mocking in the module loader. */ + function enableAutomock(): void; + /** Creates a mock function. Optionally takes a mock implementation. */ + function fn(implementation?: Function): Mock; + /** Use the automatic mocking system to generate a mocked version of the given module. */ + function genMockFromModule(moduleName: string): T; + /** Returns whether the given function is a mock function. */ + function isMockFunction(fn: any): fn is Mock; + /** Mocks a module with an auto-mocked version when it is being required. */ + function mock(moduleName: string, factory?: any, options?: MockOptions): void; + /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ + function resetModuleRegistry(): void; + /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ + function resetModules(): void; + /** Exhausts tasks queued by setImmediate(). */ + function runAllImmediates(): void; + /** Exhausts the micro-task queue (usually interfaced in node via process.nextTick). */ + function runAllTicks(): void; + /** Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()). */ + function runAllTimers(): void; + /** Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point). + * If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call. */ + function runOnlyPendingTimers(): void; + /** Explicitly supplies the mock object that the module system should return for the specified module. */ + function setMock(moduleName: string, moduleExports: T): void; + /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ + function unmock(moduleName: string): void; + /** Instructs Jest to use fake versions of the standard timer functions. */ + function useFakeTimers(): void; + /** Instructs Jest to use the real versions of the standard timer functions. */ + function useRealTimers(): void; + + interface MockOptions { + virtual?: boolean; } - interface Mock { + interface EmptyFunction { + (): void; + } + + interface DoneCallback { + (...args: any[]): any + fail(error?: string | { message: string }): any; + } + + interface ProvidesCallback { + (cb?: DoneCallback): any; + } + + interface Lifecycle { + (fn: ProvidesCallback): any; + } + + interface It { + (name: string, fn: ProvidesCallback): void; + only: It; + skip: It; + } + + interface Describe { + (name: string, fn: EmptyFunction): void + only: Describe; + skip: Describe; + } + + interface Matchers { + not: Matchers; + lastCalledWith(...args: any[]): void; + toBe(expected: any): void; + toBeCalled(): void; + toBeCalledWith(...args: any[]): void; + toBeCloseTo(expected: number, delta: number): void; + toBeDefined(): void; + toBeFalsy(): void; + toBeGreaterThan(expected: number): void; + toBeGreaterThanOrEqual(expected: number): void; + toBeInstanceOf(expected: any): void + toBeLessThan(expected: number): void; + toBeLessThanOrEqual(expected: number): void; + toBeNull(): void; + toBeTruthy(): void; + toBeUndefined(): void; + toContain(expected: any): void; + toEqual(expected: any): void; + toHaveBeenCalled(): boolean; + toHaveBeenCalledTimes(expected: number): boolean; + toHaveBeenCalledWith(...params: any[]): boolean; + toMatch(expected: string | RegExp): void; + toMatchSnapshot(): void; + toThrow(): void; + toThrowError(error?: string | Constructable | RegExp): void; + } + + interface Constructable { + new (...args: any[]): any + } + + interface Mock extends Function { new (): T; - (...args: any[]): any; // Making Mock Callable and fixing: Value of type 'Mock' is not callable. + (...args: any[]): any; mock: MockContext; mockClear(): void; mockImplementation(fn: Function): Mock; @@ -58,31 +149,145 @@ declare namespace jest { mockReturnValue(value: any): Mock; mockReturnValueOnce(value: any): Mock; } - - function clearAllTimers(): void; - function disableAutomock(): void; - function enableAutomock(): void; - function fn(implementation?: Function): Mock; - function isMockFunction(fn: Function): boolean; - function genMockFromModule(moduleName: string): T; - function mock(moduleName: string, factory?: Function, options?: {virtual: boolean}): void; - function resetModules(): void; - function runAllTicks(): void; - function runAllTimers(): void; - function runOnlyPendingTimers(): void; - function setMock(moduleName: string, moduleExports: T): void; - function unmock(moduleName: string): void; - function useFakeTimers(): void; - function useRealTimers(): void; - // taken from Jasmine which takes from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() + interface MockContext { + calls: any[][]; + instances: T[]; + } +} + +//Jest ships with a copy of Jasmine. They monkey-patch its APIs and divergence/deprecation are expected. +//Relevant parts of Jasmine's API are below so they can be changed and removed over time. +//This file can't reference jasmine.d.ts since the globals aren't compatible. + +declare function spyOn(object: any, method: string): jasmine.Spy; +/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */ +declare function pending(reason?: string): void; +/** Fails a test when called within one. */ +declare function fail(error?: any): void; +declare namespace jasmine { + var clock: () => Clock; + function any(aclass: any): Any; + function anything(): Any; + function arrayContaining(sample: any[]): ArrayContaining; + function objectContaining(sample: any): ObjectContaining; + function createSpy(name: string, originalFn?: Function): Spy; + function createSpyObj(baseName: string, methodNames: any[]): any; + function createSpyObj(baseName: string, methodNames: any[]): T; + function pp(value: any): string; + function addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + function addMatchers(matchers: CustomMatcherFactories): void; + function stringMatching(value: string | RegExp): Any; + + interface Clock { + install(): void; + uninstall(): void; + /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */ + tick(ms: number): void; + mockDate(date?: Date): void; + } + + interface Any { + new (expectedClass: any): any; + jasmineMatches(other: any): boolean; + jasmineToString(): string; + } + + interface ArrayContaining { + new (sample: any[]): any; + asymmetricMatch(other: any): boolean; + jasmineToString(): string; + } + + interface ObjectContaining { + new (sample: any): any; + jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean; + jasmineToString(): string; + } + + interface Spy { + (...params: any[]): any; + identity: string; + and: SpyAnd; + calls: Calls; + mostRecentCall: { args: any[]; }; + argsForCall: any[]; + wasCalled: boolean; + } + + interface SpyAnd { + /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */ + callThrough(): Spy; + /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */ + returnValue(val: any): Spy; + /** By chaining the spy with and.returnValues, all calls to the function will return specific values in order until it reaches the end of the return values list. */ + returnValues(...values: any[]): Spy; + /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */ + callFake(fn: Function): Spy; + /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */ + throwError(msg: string): Spy; + /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */ + stub(): Spy; + } + + interface Calls { + /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. */ + any(): boolean; + /** By chaining the spy with calls.count(), will return the number of times the spy was called */ + count(): number; + /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index */ + argsFor(index: number): any[]; + /** By chaining the spy with calls.allArgs(), will return the arguments to all calls */ + allArgs(): any[]; + /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls */ + all(): CallInfo[]; + /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call */ + mostRecent(): CallInfo; + /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call */ + first(): CallInfo; + /** By chaining the spy with calls.reset(), will clears all tracking for a spy */ + reset(): void; + } + + interface CallInfo { + /** The context (the this) for the call */ + object: any; + /** All arguments passed to the call */ + args: any[]; + /** The return value of the call */ + returnValue: any; + } + + interface CustomMatcherFactories { + [index: string]: CustomMatcherFactory; + } + + interface CustomMatcherFactory { + (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; + } + + interface MatchersUtil { + equals(a: any, b: any, customTesters?: Array): boolean; + contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; + buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; + } + + interface CustomEqualityTester { + (first: any, second: any): boolean; + } + + interface CustomMatcher { + compare(actual: T, expected: T): CustomMatcherResult; + compare(actual: any, expected: any): CustomMatcherResult; + } + + interface CustomMatcherResult { + pass: boolean; + message: string | (() => string); + } + interface ArrayLike { length: number; [n: number]: T; } } - -interface NodeRequire { - requireActual(moduleName: string): any; - requireMock(moduleName: string): any; -} From bb5916e6451594dbc565c8877dfcbfebde1c8976 Mon Sep 17 00:00:00 2001 From: pafflique Date: Mon, 19 Sep 2016 17:51:12 +0300 Subject: [PATCH 559/844] Concat second+ parameter can be plain value. --- lodash/lodash.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index eb24793955..3bdd09fab4 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -501,7 +501,7 @@ declare module _ { * console.log(array); * // => [1] */ - concat(...values: (T[]|List)[]) : T[]; + concat(array: T[]|List, ...values: (T|T[]|List)[]) : T[]; } //_.difference From 20bcf21d905410c359268df715a7c6a7771493b6 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 13:28:14 -0400 Subject: [PATCH 560/844] Removed extra constants Proj4 Projection --- proj4/proj4.d.ts | 20 +++----------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/proj4/proj4.d.ts b/proj4/proj4.d.ts index 70de08b5a6..d59063f51b 100644 --- a/proj4/proj4.d.ts +++ b/proj4/proj4.d.ts @@ -27,29 +27,15 @@ declare module "proj4" { } interface InterfaceProjection { - title: string - projName: string - ellps: string - datumCode: string - units: string - a: number - rf: number - ellipseName: string + datum: string b: number - a2: number - b2: number + rf: number + sphere: 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 { From 2ff803ff9187fc4837a79924435f2d98f8a3bdda Mon Sep 17 00:00:00 2001 From: feitzi Date: Mon, 19 Sep 2016 20:14:41 +0200 Subject: [PATCH 561/844] refactored: randomColor to randomcolor --- randomColor/randomColor.d.ts | 2 +- randomcolor/randomcolor-tests.ts | 40 ++++++++++++++++++++++++++++++++ randomcolor/randomcolor.d.ts | 28 ++++++++++++++++++++++ 3 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 randomcolor/randomcolor-tests.ts create mode 100644 randomcolor/randomcolor.d.ts diff --git a/randomColor/randomColor.d.ts b/randomColor/randomColor.d.ts index 1c52f39be1..a92af51453 100644 --- a/randomColor/randomColor.d.ts +++ b/randomColor/randomColor.d.ts @@ -23,6 +23,6 @@ interface randomColorOptions { declare var randomColor: RandomColor.RandomColorStatic; -declare module 'randomColor' { +declare module 'randomcolor' { export = randomColor; } \ No newline at end of file diff --git a/randomcolor/randomcolor-tests.ts b/randomcolor/randomcolor-tests.ts new file mode 100644 index 0000000000..69b617615e --- /dev/null +++ b/randomcolor/randomcolor-tests.ts @@ -0,0 +1,40 @@ +/// + +// Returns a hex code for an attractive color +randomColor(); + +// Returns an array of ten green colors +randomColor({ + count: 10, + hue: 'green' +}); + +// Returns a hex code for a light blue +randomColor({ + luminosity: 'light', + hue: 'blue' +}); + +// Returns a hex code for a 'truly random' color +randomColor({ + luminosity: 'random', + hue: 'random' +}); + +// Returns a bright color in RGB +randomColor({ + luminosity: 'bright', + format: 'rgb' // e.g. 'rgb(225,200,20)' +}); + +// Returns a dark RGB color with random alpha +randomColor({ + luminosity: 'dark', + format: 'rgba' // e.g. 'rgba(9, 1, 107, 0.6482447960879654)' +}); + +// Returns a light HSL color with random alpha +randomColor({ + luminosity: 'light', + format: 'hsla' // e.g. 'hsla(27, 88.99%, 81.83%, 0.6450211517512798)' +}); \ No newline at end of file diff --git a/randomcolor/randomcolor.d.ts b/randomcolor/randomcolor.d.ts new file mode 100644 index 0000000000..a92af51453 --- /dev/null +++ b/randomcolor/randomcolor.d.ts @@ -0,0 +1,28 @@ +// Type definitions for randomColor 0.4.1 +// Project: https://github.com/davidmerfield/randomColor +// Definitions by: Mathias Feitzinger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace RandomColor { + + interface RandomColorStatic { + + () : string; + + (options : randomColorOptions): string; +} + +interface randomColorOptions { + hue? : string; + luminosity? : string; + count? : string | number; + seed?: string; + format?: string; + } +} + +declare var randomColor: RandomColor.RandomColorStatic; + +declare module 'randomcolor' { + export = randomColor; +} \ No newline at end of file From 8571feee2f68b8971ee02acbe60021d368ba4136 Mon Sep 17 00:00:00 2001 From: feitzi Date: Mon, 19 Sep 2016 20:18:33 +0200 Subject: [PATCH 562/844] fixed wrong reference path --- randomColor/randomColor-tests.ts | 2 +- randomcolor/randomcolor-tests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/randomColor/randomColor-tests.ts b/randomColor/randomColor-tests.ts index 69b617615e..4dfd6bed26 100644 --- a/randomColor/randomColor-tests.ts +++ b/randomColor/randomColor-tests.ts @@ -1,4 +1,4 @@ -/// +/// // Returns a hex code for an attractive color randomColor(); diff --git a/randomcolor/randomcolor-tests.ts b/randomcolor/randomcolor-tests.ts index 69b617615e..4dfd6bed26 100644 --- a/randomcolor/randomcolor-tests.ts +++ b/randomcolor/randomcolor-tests.ts @@ -1,4 +1,4 @@ -/// +/// // Returns a hex code for an attractive color randomColor(); From 24c81fd722b734b793ea7acd7aca0fddebe47c71 Mon Sep 17 00:00:00 2001 From: feitzi Date: Mon, 19 Sep 2016 20:36:32 +0200 Subject: [PATCH 563/844] fixed renaming folder --- {randomColor => randomcolor}/randomColor-tests.ts | 0 {randomColor => randomcolor}/randomColor.d.ts | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {randomColor => randomcolor}/randomColor-tests.ts (100%) rename {randomColor => randomcolor}/randomColor.d.ts (100%) diff --git a/randomColor/randomColor-tests.ts b/randomcolor/randomColor-tests.ts similarity index 100% rename from randomColor/randomColor-tests.ts rename to randomcolor/randomColor-tests.ts diff --git a/randomColor/randomColor.d.ts b/randomcolor/randomColor.d.ts similarity index 100% rename from randomColor/randomColor.d.ts rename to randomcolor/randomColor.d.ts From 66c9d1c4ba7246540618d831355eaf2ced60d48e Mon Sep 17 00:00:00 2001 From: Marc Date: Mon, 19 Sep 2016 14:56:14 -0400 Subject: [PATCH 564/844] Fix asked by andy-ms --- requirejs/require.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 3c807897ddb2a74d4497defb96a1ba5b86d55d9f Mon Sep 17 00:00:00 2001 From: Nao Ohira Date: Mon, 19 Sep 2016 20:57:14 +0200 Subject: [PATCH 565/844] Add bulkDocs types --- pouchdb-core/pouchdb-core.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pouchdb-core/pouchdb-core.d.ts b/pouchdb-core/pouchdb-core.d.ts index b0498e76af..2fa4737fa6 100644 --- a/pouchdb-core/pouchdb-core.d.ts +++ b/pouchdb-core/pouchdb-core.d.ts @@ -268,6 +268,12 @@ declare namespace PouchDB { allDocs(options?: Core.AllDocsOptions): Promise>; + bulkDocs(docs: Core.Document[], + options: Core.PutOptions | void, + callback: Core.Callback): void; + bulkDocs(docs: Core.Document[], + options: Core.PutOptions | void): Promise; + /** Compact the database */ compact(options?: Core.CompactOptions): Promise; compact(options: Core.CompactOptions, From 0fa2d359311a996084dc3bb67a80365992e3ba42 Mon Sep 17 00:00:00 2001 From: Nao Ohira Date: Mon, 19 Sep 2016 21:09:57 +0200 Subject: [PATCH 566/844] Fix bulkDocs signature with Promise response --- pouchdb-core/pouchdb-core.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pouchdb-core/pouchdb-core.d.ts b/pouchdb-core/pouchdb-core.d.ts index 2fa4737fa6..cdd078f54f 100644 --- a/pouchdb-core/pouchdb-core.d.ts +++ b/pouchdb-core/pouchdb-core.d.ts @@ -272,7 +272,7 @@ declare namespace PouchDB { options: Core.PutOptions | void, callback: Core.Callback): void; bulkDocs(docs: Core.Document[], - options: Core.PutOptions | void): Promise; + options?: Core.PutOptions): Promise; /** Compact the database */ compact(options?: Core.CompactOptions): Promise; From a1610b0485969380bdc09cd411f0965c8c1569ce Mon Sep 17 00:00:00 2001 From: Nao Ohira Date: Mon, 19 Sep 2016 21:29:07 +0200 Subject: [PATCH 567/844] Add test for bulkDocs --- pouchdb-core/pouchdb-core-tests.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/pouchdb-core/pouchdb-core-tests.ts b/pouchdb-core/pouchdb-core-tests.ts index b46bce834d..3da5e929b7 100644 --- a/pouchdb-core/pouchdb-core-tests.ts +++ b/pouchdb-core/pouchdb-core-tests.ts @@ -38,6 +38,23 @@ namespace PouchDBCoreTests { }); } + function testBulkDocs() { + const db = new PouchDB(); + type MyModel = { property: 'someProperty '}; + let model: PouchDB.Core.Document; + let model2: PouchDB.Core.Document; + + db.bulkDocs([model, model2]).then((result) => { + result.forEach(({ ok, id, rev }) => { + isString(id); + isString(rev); + }); + }); + + db.bulkDocs([model, model2], null, (error, response) => { + }); + } + function testCompact() { const db = new PouchDB<{}>(); // Promise version From 0a9c6b435c24fa0f07a62beb2c7d43b98914bc21 Mon Sep 17 00:00:00 2001 From: David Poetzsch-Heffter Date: Tue, 20 Sep 2016 00:24:55 +0200 Subject: [PATCH 568/844] added typings for parse-mockdb --- parse-mockdb/parse-mockdb-tests.ts | 25 +++++++++++++++++++++++++ parse-mockdb/parse-mockdb.d.ts | 21 +++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 parse-mockdb/parse-mockdb-tests.ts create mode 100644 parse-mockdb/parse-mockdb.d.ts diff --git a/parse-mockdb/parse-mockdb-tests.ts b/parse-mockdb/parse-mockdb-tests.ts new file mode 100644 index 0000000000..89f586d9e8 --- /dev/null +++ b/parse-mockdb/parse-mockdb-tests.ts @@ -0,0 +1,25 @@ +/// + +ParseMockDB.mockDB(); // Mock the Parse RESTController + +// from parse-mockdb test suite +ParseMockDB.registerHook("Foo", "beforeSave", (request) => { + const object = request.object; + if (object.get('error')) { + return Parse.Promise.error('whoah'); + } + object.set('cool', true); + return Parse.Promise.as(object); +}); + +// from parse-mockdb test suite +ParseMockDB.registerHook("Foo", "beforeDelete", (request) => { + const object = request.object; + if (object.get('error')) { + return Parse.Promise.error('whoah'); + } + return Parse.Promise.as({}); +}); + +ParseMockDB.cleanUp(); // Clear the Database +ParseMockDB.unMockDB(); // Un-mock the Parse RESTController diff --git a/parse-mockdb/parse-mockdb.d.ts b/parse-mockdb/parse-mockdb.d.ts new file mode 100644 index 0000000000..c6b6e729d1 --- /dev/null +++ b/parse-mockdb/parse-mockdb.d.ts @@ -0,0 +1,21 @@ +// Type definitions for parse-mockdb v0.1.13 +// Project: https://github.com/HustleInc/parse-mockdb +// Definitions by: David Poetzsch-Heffter +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace ParseMockDB { + function mockDB(): void; + function unMockDB(): void; + function cleanUp(): void; + + function promiseResultSync(promise: Parse.IPromise): T; + + type HookType = "beforeSave" | "beforeDelete"; + function registerHook(className: string, hookType: HookType, hookFn: (request: Parse.Cloud.BeforeSaveRequest) => Parse.IPromise): void; +} + +declare module "parse-mockdb" { + export = ParseMockDB; +} From e822a596e4a68bd8a7e4a9f49f2ea95f6c25972d Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 18:54:46 -0400 Subject: [PATCH 569/844] Replace deprecated module keyword --- twilio/twilio.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index d6c2dfebf7..d6af461760 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -16,7 +16,7 @@ declare interface twilio { (sid?: string, tkn?: string, options?: twilio.ClientOptions): twilio.RestClient; } -declare module twilio { +declare namespace twilio { // Composite Classes: //============================== @@ -166,7 +166,7 @@ declare module twilio { clientName: string; outgoingScopeParams: any; scopeParams: any; - + constructor(sid?: string, tkn?: string); allowClientIncoming(clientName: string): Capability; @@ -319,7 +319,7 @@ declare module twilio { allowWorkerActivityUpdates(): void; allowWorkerFetchAttributes(): void; allowTaskReservationUpdates(): void; - + addPolicy(url: string, method: string, allowed?: boolean, queryFilter?: any, postFilter?: any): void; allow(url: string, method: string, queryFilter?: any, postFilter?: any): void; deny(url: string, method: string, queryFilter?: any, postFilter?: any): void; @@ -380,7 +380,7 @@ declare module twilio { } export interface TwimlMethod { (arg1: any | string | TwimlCallback, arg2?: any | string | TwimlCallback): Node } - + export interface TwimlCallback { (node?: Node): void; } export class Node implements NodeOptions { @@ -435,7 +435,7 @@ declare module twilio { export interface WebhookExpressOptions { // The full URL (with query string) you used to configure the webhook with Twilio - overrides host/protocol options url?: string; - + // manually specify the host name used by Twilio in a number's webhook config host?: string; From d705c4e9da0030cc11387bca31e42ddc7809ff04 Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 18:55:03 -0400 Subject: [PATCH 570/844] Add missing `webhook()` signature --- twilio/twilio-tests.ts | 2 +- twilio/twilio.d.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/twilio/twilio-tests.ts b/twilio/twilio-tests.ts index 30e9892078..d7f2c60993 100644 --- a/twilio/twilio-tests.ts +++ b/twilio/twilio-tests.ts @@ -228,5 +228,5 @@ twilio.validateRequest(token, str, 'http://example.herokuapp.com', { query: 'val twilio.validateExpressRequest({}, 'YOUR_TWILIO_AUTH_TOKEN'); twilio.validateExpressRequest({}, 'YOUR_TWILIO_AUTH_TOKEN', {}); twilio.webhook({ validate: false }); - +twilio.webhook("MYAUTHTOKEN", { validate: false }); diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index d6af461760..8bd6911113 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -446,7 +446,8 @@ declare namespace twilio { // For interop with node middleware chains export interface MiddlewareFunction { (request: Http.ClientRequest, response: Http.ClientResponse, next: MiddlewareFunction): void; } - export function webhook(options?: string | webhookOptions): MiddlewareFunction; + export function webhook(authToken: string, options?: webhookOptions): MiddlewareFunction; + export function webhook(options?: 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; From 6164f95bb173936a3a10396a01a30242ebc54bfa Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 18:58:03 -0400 Subject: [PATCH 571/844] Fix MiddlewareFunction interface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Change client request/response to server request/response, because the client ones are for when node is acting as a client (making outgoing requests), whereas here it’s acting as a server. This change is needed to work with express. 2. Change the `next` argument, because next (in express) is a function called with 0 or 1 arguments, where that argument can be an any (for the error). Next is decidedly *not* a function with the MiddlewareFunction signature. 3. Import express with a capital E, for consistency with Http, since we’re using it for its namespace. --- twilio/twilio.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index 8bd6911113..a13352b213 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -7,7 +7,7 @@ /// /// -import * as express from 'express'; +import * as Express from 'express'; import * as Http from 'http'; import q = require('q'); @@ -444,13 +444,13 @@ declare namespace twilio { } // For interop with node middleware chains - export interface MiddlewareFunction { (request: Http.ClientRequest, response: Http.ClientResponse, next: MiddlewareFunction): void; } + export interface MiddlewareFunction { (request: Http.ServerRequest, response: Http.ServerResponse, next: Express.NextFunction): void; } export function webhook(authToken: string, options?: webhookOptions): MiddlewareFunction; export function webhook(options?: 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 { From ae92456e05814ba09d5d8d6770d17048dbb960e4 Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Tue, 13 Sep 2016 16:47:05 -0400 Subject: [PATCH 572/844] In TwimlCallback, Node shouldn't be optional Because the callback is always called with the Node. This change is based on the advice here: https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/decla ration%20files/Do's%20and%20Don'ts.md#optional-parameters-in-callbacks --- twilio/twilio.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index a13352b213..84c0d02394 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -381,7 +381,7 @@ declare namespace twilio { export interface TwimlMethod { (arg1: any | string | TwimlCallback, arg2?: any | string | TwimlCallback): Node } - export interface TwimlCallback { (node?: Node): void; } + export interface TwimlCallback { (node: Node): void; } export class Node implements NodeOptions { name: string; From 3d032bd51037f5edfd008c1cfb3acf96a11138a1 Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Tue, 13 Sep 2016 17:02:08 -0400 Subject: [PATCH 573/844] Split up TwimlMethod signature By splitting up the union into an overload, we get much more useful typing than just (any, any) --- twilio/twilio.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index 84c0d02394..8d5c44984b 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -379,7 +379,10 @@ declare namespace twilio { legalNodes: Array; } - export interface TwimlMethod { (arg1: any | string | TwimlCallback, arg2?: any | string | TwimlCallback): Node } + export interface TwimlMethod { + (arg1: TwimlCallback | string, arg2?: any): Node + (arg1: any, arg2?: TwimlCallback | string): Node + } export interface TwimlCallback { (node: Node): void; } From 92b719193832e5f4bcfdb529187176de675860ff Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 19:00:58 -0400 Subject: [PATCH 574/844] Allow TwimlMethods with no arguments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit E.g. hangup() doesn’t take any arguments. --- twilio/twilio-tests.ts | 2 ++ twilio/twilio.d.ts | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/twilio/twilio-tests.ts b/twilio/twilio-tests.ts index d7f2c60993..1fb9afa0a4 100644 --- a/twilio/twilio-tests.ts +++ b/twilio/twilio-tests.ts @@ -212,6 +212,8 @@ resp.say('Your conference call is starting.', }); }); +resp.hangup(); + /// Capabilities var capability = new twilio.Capability(str, str); capability.allowClientIncoming('jenny'); diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index 8d5c44984b..c0f16211f5 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -380,8 +380,9 @@ declare namespace twilio { } export interface TwimlMethod { - (arg1: TwimlCallback | string, arg2?: any): Node - (arg1: any, arg2?: TwimlCallback | string): Node + (): Node; + (arg1: TwimlCallback | string, arg2?: any): Node; + (arg1: any, arg2?: TwimlCallback | string): Node; } export interface TwimlCallback { (node: Node): void; } From 895592ef94f5d192e3f861646d258d5362c1b8ce Mon Sep 17 00:00:00 2001 From: Simon Date: Mon, 19 Sep 2016 20:11:18 -0400 Subject: [PATCH 575/844] fixes model.discriminator() signature fixes #11323 fixes #10878 --- mongoose/mongoose-tests.ts | 15 +++++++++++++-- mongoose/mongoose.d.ts | 2 +- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 5feb08b446..03dde5759b 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1124,7 +1124,6 @@ MongoModel.create([{ type: 'jelly bean' }, { arg[0].save(); arg[1].save(); }); -MongoModel.discriminator('M', new mongoose.Schema({name: String})); MongoModel.distinct('url', { clicks: {$gt: 100}}, function (err, result) { }); MongoModel.distinct('url').exec(cb); @@ -1386,4 +1385,16 @@ Final2.staticMethod(); Final2.staticProp; var final2 = new Final2(); final2.prop; -final2.method; \ No newline at end of file +final2.method; +interface ibase extends mongoose.Document { + username: string; +} +interface extended extends ibase { + email: string; +} +const base: mongoose.Model = mongoose.model('testfour', null) +const extended: mongoose.Model = base.discriminator('extendedS', null); +const x = new extended({ + username: 'hi', // required in baseSchema + email: 'beddiw', // required in extededSchema +}) \ No newline at end of file diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 2d0046ea8c..6456fdc003 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2119,7 +2119,7 @@ declare module "mongoose" { * @param name discriminator model name * @param schema discriminator model schema */ - discriminator(name: string, schema: Schema): T; + discriminator(name: string, schema: Schema): Model; /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */ distinct(field: string, callback?: (err: any, res: any[]) => void): Query; From b434572f41b4d9e734a2322209f08d1384dca83c Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 23:04:50 -0400 Subject: [PATCH 576/844] fixup tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Note that these tests aren’t currently passing on master either; the last PR only passed because travis didn’t actually run the tests: https://travis-ci.org/DefinitelyTyped/DefinitelyTyped/builds/160110579 --- twilio/twilio-tests.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/twilio/twilio-tests.ts b/twilio/twilio-tests.ts index 1fb9afa0a4..25c6915068 100644 --- a/twilio/twilio-tests.ts +++ b/twilio/twilio-tests.ts @@ -1,4 +1,5 @@ import * as twilio from './twilio'; +import * as Express from "express"; // Examples taken from https://twilio.github.io/twilio-node/ (v2.1.0) @@ -227,8 +228,12 @@ var token = capability.generate(120); /// Utilities twilio.validateRequest(token, str, 'http://example.herokuapp.com', { query: 'val' }); -twilio.validateExpressRequest({}, 'YOUR_TWILIO_AUTH_TOKEN'); -twilio.validateExpressRequest({}, 'YOUR_TWILIO_AUTH_TOKEN', {}); +twilio.validateExpressRequest(getMockExpressRequest(), 'YOUR_TWILIO_AUTH_TOKEN'); +twilio.validateExpressRequest(getMockExpressRequest(), 'YOUR_TWILIO_AUTH_TOKEN', {}); twilio.webhook({ validate: false }); twilio.webhook("MYAUTHTOKEN", { validate: false }); + +function getMockExpressRequest(): Express.Request { + return JSON.parse("{}"); +} From 6ce6486f526de4709114458fb4362303c7658659 Mon Sep 17 00:00:00 2001 From: danderson00 Date: Mon, 19 Sep 2016 22:30:59 -0700 Subject: [PATCH 577/844] Update to 3.0.0 --- azure-mobile-apps/azure-mobile-apps-tests.ts | 39 +++++++++--- azure-mobile-apps/azure-mobile-apps.d.ts | 66 ++++++++++++++------ 2 files changed, 77 insertions(+), 28 deletions(-) diff --git a/azure-mobile-apps/azure-mobile-apps-tests.ts b/azure-mobile-apps/azure-mobile-apps-tests.ts index 302f732889..f8f3bcef52 100644 --- a/azure-mobile-apps/azure-mobile-apps-tests.ts +++ b/azure-mobile-apps/azure-mobile-apps-tests.ts @@ -8,7 +8,7 @@ import queries = require('azure-mobile-apps/src/query'); var app = express(), mobileApp = mobileApps(); -// various configuration permutations +// various configuration permutations mobileApps({ debug: true, data: { @@ -17,7 +17,8 @@ mobileApps({ user: '', database: '', password: '' - } + }, + webhook: { url: 'http://localhost/' } }); mobileApps({ @@ -29,7 +30,7 @@ mobileApps({ // it would be nice to integrate with winston mobileApps({ logging: { level: 'silly', transports: [{}] } }) -// various custom middleware syntaxes +// various custom middleware syntaxes mobileApp.use(function (req: any, res: any, next: any) { next(); }); mobileApp.use([function () {}, function () {}]); mobileApp.use(function () {}, function () {}); @@ -43,6 +44,9 @@ mobileApp.tables.import('tables'); mobileApp.api.add('api', { authorize: true, get: function () {}, delete: function () {} }); mobileApp.api.import('api'); +// ensure the mobile app instance can be correctly mounted as an express router +app.use(mobileApp); + // Express.Table, instantiated from the mobile app var table = mobileApp.table() table.use(function (req: Express.Request, res: Express.Response, next: any) { @@ -61,16 +65,18 @@ table.read(function (context: Azure.MobileApps.Context) { table.insert(function (context: Azure.MobileApps.Context) { context.query.id = 'anotherId'; context.query.single = true; - context.item.userId = context.user.id; + context.item.userId = context.user.id; context.push.send('tag', {}, function (error, result) {}); context.push.gcm.send('tag', {}, function (error, result) {}); context.push.apns.send('tag', { payload: { } }, function (error, result) {}); context.push.wns.sendToastText01('tag', '', { headers: { } }, function (error, result) {}); + context.next(new Error()); + context.next('An error occurred'); }); table.read.use(function () {}); table.read.use([function () {}, function () {}]); table.read.use(function () {}, function () {}); -table.use(function () {}).use(function () {}).read(function () {}).use(function () {}) +table.use(function () {}).use(function () {}).read(function () {}).use(function () {}); table.access = undefined; table.access = 'authenticated'; @@ -79,10 +85,25 @@ table.update.access = 'disabled'; table.delete.access = 'authenticated'; table.insert.access = 'authenticated'; +table.filters = [function (query, context) { }]; +table.transforms = [function (item, context) { }]; +table.hooks = [function (results, context) { }]; + +table.perUser = true; +table.recordsExpire = { milliseconds: 1, seconds: 1, minutes: 1, hours: 1, days: 1, weeks: 1, months: 1, years: 1 }; +table.webhook = { url: 'http://localhost/' } +table.webhook = true; + // 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(); -table2.read(function (context: Azure.MobileApps.Context) {}) +table2.read(function (context: Azure.MobileApps.Context) {}); + +// ApiDefinition, from the static require('azure-mobile-apps').api() +var api2 = mobileApps.api({ + get: function (req, res, next) { } +}); +api2.post = function (req, res, next) {}; // Logger logger.silly('test', 'message'); @@ -90,10 +111,10 @@ logger.error('Something happened', new Error()); mobileApps.logger.debug('a debug message') // Query -queries.create('table').where({ x: 10 }).select('col1,col2'); +queries.create('table').where({ x: 10 }).select('col1,col2').includeDeleted().includeTotalCount(); mobileApps.query.create('table'); -// custom sql query +// Custom SQL query mobileApp.api.add('query', { authorize: true, get: (req, res, next) => { req.azureMobile.data.execute({ sql: "SELECT * FROM TODOITEM WHERE COMPLETE = :complete", @@ -101,4 +122,4 @@ mobileApp.api.add('query', { authorize: true, get: (req, res, next) => { { name: 'complete', value: 1 } ] }).then(x => {}); -}, delete: function () {} }); +}, delete: function () {} }); diff --git a/azure-mobile-apps/azure-mobile-apps.d.ts b/azure-mobile-apps/azure-mobile-apps.d.ts index a17e41e2d6..4731d91eb2 100644 --- a/azure-mobile-apps/azure-mobile-apps.d.ts +++ b/azure-mobile-apps/azure-mobile-apps.d.ts @@ -1,4 +1,4 @@ -// Type definitions for azure-mobile-apps v2.0.0-beta3 +// Type definitions for azure-mobile-apps v2.1.7 // Project: https://github.com/Azure/azure-mobile-apps-node/ // Definitions by: Microsoft Azure // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,6 +10,7 @@ declare module "azure-mobile-apps" { interface AzureMobileApps { (configuration?: Azure.MobileApps.Configuration): Azure.MobileApps.Platforms.Express.MobileApp; table(): Azure.MobileApps.Platforms.Express.Table; + api(definition?: Azure.MobileApps.ApiDefinition): Azure.MobileApps.ApiDefinition; logger: Azure.MobileApps.Logger; query: Azure.MobileApps.Query; } @@ -31,7 +32,7 @@ declare namespace Azure.MobileApps { // the additional Platforms namespace is required to avoid collisions with the main Express namespace export module Platforms { export module Express { - interface MobileApp { + interface MobileApp extends Middleware { configuration: Configuration; tables: Tables; table(): Table; @@ -45,15 +46,7 @@ declare namespace Azure.MobileApps { import(fileOrFolder: string): void; } - interface Table { - authorize?: boolean; - access?: AccessType; - autoIncrement?: boolean; - dynamicSchema?: boolean; - name: string; - columns?: any; - schema: string; - + interface Table extends TableDefinition { use(...middleware: Middleware[]): Table; use(middleware: Middleware[]): Table; read: TableOperation; @@ -67,11 +60,9 @@ declare namespace Azure.MobileApps { (operationHandler: (context: Context) => void): Table; use(...middleware: Middleware[]): Table; use(middleware: Middleware[]): Table; - access: AccessType; + access?: AccessType; } - type AccessType = 'anonymous' | 'authenticated' | 'disabled'; - interface Tables { configuration: Configuration; add(name: string, definition?: Table | TableDefinition): void; @@ -136,6 +127,7 @@ declare namespace Azure.MobileApps { auth?: Configuration.Auth; cors?: Configuration.Cors; notifications?: Configuration.Notifications; + webhook?: Webhook; } export module Configuration { @@ -152,6 +144,7 @@ declare namespace Azure.MobileApps { options?: { encrypt: boolean }; schema?: string; dynamicSchema?: boolean; + filename?: string; } interface Auth { @@ -167,8 +160,9 @@ declare namespace Azure.MobileApps { interface LoggingTransport { } interface Cors { + exposeHeaders: string; maxAge?: number; - origins: string[]; + hostnames: string[]; } interface Notifications { @@ -188,7 +182,8 @@ declare namespace Azure.MobileApps { } interface QueryJs { - includeTotalCount?: boolean; + includeTotalCount(): QueryJs; + includeDeleted(): QueryJs; orderBy(properties: string): QueryJs; orderByDescending(properties: string): QueryJs; select(properties: string): QueryJs; @@ -213,6 +208,7 @@ declare namespace Azure.MobileApps { // general var nh: Azure.ServiceBus.NotificationHubService; + interface Context { query: QueryJs; id: string | number; @@ -225,6 +221,7 @@ declare namespace Azure.MobileApps { push: typeof nh; logger: Logger; execute(): Thenable; + next(error: string|Error): any; } interface ContextData { @@ -240,15 +237,46 @@ declare namespace Azure.MobileApps { interface SqlParameterDefinition { name: string; value: any; - } + } interface TableDefinition { + access?: AccessType; authorize?: boolean; autoIncrement?: boolean; - dynamicSchema?: boolean; - name?: string; columns?: any; + databaseTableName?: string; + dynamicSchema?: boolean; + maxTop?: number; + name?: string; + pageSize?: number; schema?: string; + softDelete?: boolean; + userIdColumn?: string; + + filters?: [(QueryJs, Context) => void | QueryJs]; + transforms?: [(any, Context) => void | any]; + hooks?: [(any, Context) => void]; + + perUser?: boolean; + recordsExpire?: Duration; + webhook?: Webhook | boolean; + } + + type AccessType = 'anonymous' | 'authenticated' | 'disabled'; + + interface Duration { + milliseconds?: number; + seconds?: number; + minutes?: number; + hours?: number; + days?: number; + weeks?: number; + months?: number; + years?: number; + } + + interface Webhook { + url: string; } interface ApiDefinition { From 4b32d529eba572b91620986d3193e60d77f65c63 Mon Sep 17 00:00:00 2001 From: akankov Date: Tue, 20 Sep 2016 12:48:54 +0700 Subject: [PATCH 578/844] fromData type fix --- dropzone/dropzone.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/dropzone/dropzone.d.ts b/dropzone/dropzone.d.ts index 7464151b3b..ff8412b0e8 100644 --- a/dropzone/dropzone.d.ts +++ b/dropzone/dropzone.d.ts @@ -95,8 +95,8 @@ interface DropzoneOptions { uploadprogress?(file:DropzoneFile, progress:number, bytesSent:number):void; totaluploadprogress?(totalProgress:number, totalBytes:number, totalBytesSent:number):void; - sending?(file:DropzoneFile, xhr:XMLHttpRequest, formData:{}):void; - sendingmultiple?(files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}):void; + sending?(file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData):void; + sendingmultiple?(files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData):void; success?(file: DropzoneFile, response: Object|string): void; successmultiple?(files:DropzoneFile[], responseText:string):void; @@ -206,8 +206,8 @@ declare class Dropzone { on(eventName:"uploadprogress", callback:(file:DropzoneFile, progress:number, bytesSent:number) => any):void; on(eventName:"totaluploadprogress", callback:(totalProgress:number, totalBytes:number, totalBytesSent:number) => any):void; - on(eventName:"sending", callback:(file:DropzoneFile, xhr:XMLHttpRequest, formData:{}) => any):void; - on(eventName:"sendingmultiple", callback:(files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}) => any):void; + on(eventName:"sending", callback:(file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData) => any):void; + on(eventName:"sendingmultiple", callback:(files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData) => any):void; on(eventName:"success", callback:(file:DropzoneFile) => any):void; on(eventName:"successmultiple", callback:(files:DropzoneFile[]) => any):void; @@ -246,8 +246,8 @@ declare class Dropzone { emit(eventName:"uploadprogress", file:DropzoneFile, progress:number, bytesSent:number):void; emit(eventName:"totaluploadprogress", totalProgress:number, totalBytes:number, totalBytesSent:number):void; - emit(eventName:"sending", file:DropzoneFile, xhr:XMLHttpRequest, formData:{}):void; - emit(eventName:"sendingmultiple", files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}):void; + emit(eventName:"sending", file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData):void; + emit(eventName:"sendingmultiple", files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData):void; emit(eventName:"success", file:DropzoneFile):void; emit(eventName:"successmultiple", files:DropzoneFile[]):void; From 6eaf28d3038a399f3724d831c86f4d525feace69 Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Fri, 16 Sep 2016 14:32:42 +0300 Subject: [PATCH 579/844] Add justifyContent to CssProperties `justifyContent ` was missing from CssProperties and this PR adds it. More information about it [here](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content). --- react/react.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/react/react.d.ts b/react/react.d.ts index 5178ad28a6..30ab2db256 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -1181,6 +1181,12 @@ declare namespace __React { imeMode?: any; + /** + * Defines how the browser distributes space between and around flex items + * along the main-axis of their container. + */ + justifyContent?: "flex-start" | "flex-end" | "center" | "space-between" | "space-around"; + layoutGrid?: any; layoutGridChar?: any; From 708b7be87332bd42d9d0db5db0398a95beae4e41 Mon Sep 17 00:00:00 2001 From: danderson00 Date: Mon, 19 Sep 2016 23:04:19 -0700 Subject: [PATCH 580/844] Fix hook function types --- azure-mobile-apps/azure-mobile-apps.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/azure-mobile-apps/azure-mobile-apps.d.ts b/azure-mobile-apps/azure-mobile-apps.d.ts index 4731d91eb2..54aaa66f8b 100644 --- a/azure-mobile-apps/azure-mobile-apps.d.ts +++ b/azure-mobile-apps/azure-mobile-apps.d.ts @@ -253,9 +253,9 @@ declare namespace Azure.MobileApps { softDelete?: boolean; userIdColumn?: string; - filters?: [(QueryJs, Context) => void | QueryJs]; - transforms?: [(any, Context) => void | any]; - hooks?: [(any, Context) => void]; + filters?: [(query: QueryJs, context: Context) => void | QueryJs]; + transforms?: [(item: any, context: Context) => void | any]; + hooks?: [(results: any, context: Context) => void]; perUser?: boolean; recordsExpire?: Duration; From 3dacedf0dc0f6c539dfb2751232d25a868752d54 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 11:33:29 +0300 Subject: [PATCH 581/844] Create index.d.ts --- react-redux-toastr/index.d.ts | 105 ++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 react-redux-toastr/index.d.ts diff --git a/react-redux-toastr/index.d.ts b/react-redux-toastr/index.d.ts new file mode 100644 index 0000000000..fb3dabfa61 --- /dev/null +++ b/react-redux-toastr/index.d.ts @@ -0,0 +1,105 @@ +// Type definitions for react-redux-toastr 3.7.0 +// Project: https://github.com/diegoddox/react-redux-toastr +// Definitions by: Aleksandar Ivanov https://github.com/Smiche +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module "react-redux-toastr" { + import R = __React; + import _Redux = Redux; + + interface ToastrOptions { + /** + * Timeout in miliseconds. + */ + timeOut?: number, + /** + * Show newest on top or bottom. + */ + newestOnTop?: boolean, + /** + * Position of the toastr: top-left, top-center, top-right, bottom-left, bottom-center and bottom-right + */ + position?: string, + confirmText?: ConfirmText + } + + interface ConfirmText { + okText: string, + cancelText: string + } + + /** + * Toastr react component. + */ + export default class ReduxToastr extends R.Component{ } + + interface EmitterOptions { + /** + * Notification popup icon. + * icon-close-round, icon-information-circle, icon-check-1, icon-exclamation-triangle, icon-exclamation-alert + */ + icon?: string, + /** + * Timeout in miliseconds. + */ + timeOut?: number, + removeOnHover?: boolean, + removeOnClick?: boolean, + component?: R.Component, + onShowComplete?: () => void, + onHideComplete?: () => void + } + + interface ToastrConfirmOptions { + onOk: () => void, + onCancel: () => void + } + + interface ToastrEmitter { + /** + * Used to provide a large amount of information. + * It will not close unless a timeOut is provided. + */ + message: (title: string, message: string, options?: EmitterOptions) => void, + info: (title: string, message: string, options?: EmitterOptions) => void, + success: (title: string, message: string, options?: EmitterOptions) => void, + warning: (title: string, message: string, options?: EmitterOptions) => void, + error: (title: string, message: string, options?: EmitterOptions) => void, + /** + * Clear all notifications + */ + clean: () => void, + /** + * Hook confirmation toastr with callback. + */ + confirm: (message: string, options: ToastrConfirmOptions) => any + } + + /** + * Possible actions to dispatch. + */ + interface Actions { + addToastrAction: Redux.Action, + clean: Redux.Action, + remove: Redux.Action, + success: Redux.Action, + info: Redux.Action, + warning: Redux.Action, + error: Redux.Action, + showConfirm: Redux.Action, + hideConfirm: Redux.Action + } + + /** + * Action creator for toastr. + */ + export var actions: Redux.ActionCreator; + /** + * Reducer for the toastr state. + * Combine with your reducers. + */ + export var reducer: Redux.Reducer; + /** + * Used to issue toastr notifications. + */ + export var toastr: ToastrEmitter; +} From 60b8d4769542d602022d0a7c521ac69ae7aff4ea Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 11:34:07 +0300 Subject: [PATCH 582/844] Create library-tests.ts --- react-redux-toastr/library-tests.ts | 51 +++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 react-redux-toastr/library-tests.ts diff --git a/react-redux-toastr/library-tests.ts b/react-redux-toastr/library-tests.ts new file mode 100644 index 0000000000..427823b7c1 --- /dev/null +++ b/react-redux-toastr/library-tests.ts @@ -0,0 +1,51 @@ +/// +/// +/// +/// +import {toastr, reducer as toastrReducer, actions} from 'react-redux-toastr'; +import ReduxToastr from 'react-redux-toastr'; +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import {createStore, combineReducers, bindActionCreators} from 'redux'; +import { Provider, connect } from 'react-redux'; + +function test() { + const store = createStore(combineReducers({ toastr: toastrReducer })); + var toastrFactory = React.createFactory(ReduxToastr); + var element = toastrFactory({ timeOut: 1000, newestOnTop: false }); + var providerFactory = React.createFactory(Provider); + var root = providerFactory({ store: store }, element); + + class Test extends React.Component{ + private toastr; + constructor() { + super() + this.toastr = bindActionCreators(actions, this.props.dispatch); + this.toastr.clean(); + this.toastr.success("hi"); + } + + } + + + var TestComponent = connect(mapStateToProps, mapDispatchToProps)(Test); + function mapDispatchToProps(dispatch) { + return { + actions: bindActionCreators(actions, dispatch) + }; + } + + function mapStateToProps(state) { + return {}; + } + + function callback() { } + + toastr.clean(); + toastr.confirm("Test", { onOk: callback, onCancel: callback }); + toastr.error("Error", "Error message"); + toastr.info("Info", "Info test", { timeOut: 1000, removeOnHover: true, removeOnClick: true, onShowComplete: callback }); + toastr.success("Test", "Test message", { component: new React.Component() }); +} + +test(); From ab8d917787092fdfb16390f2bee6de8ab5c1783c Mon Sep 17 00:00:00 2001 From: Jay Anslow Date: Tue, 20 Sep 2016 09:55:32 +0100 Subject: [PATCH 583/844] Node.JS EventEmitter accepts symbols as event names. --- node/node-tests.ts | 4 ++-- node/node.d.ts | 46 +++++++++++++++++++++++----------------------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index 1fcf149e99..da3721c3aa 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -70,7 +70,7 @@ namespace assert_tests { namespace events_tests { let emitter: events.EventEmitter; - let event: string; + let event: string|symbol; let listener: Function; let any: any; @@ -114,7 +114,7 @@ namespace events_tests { } { - let result: string[]; + let result: (string|symbol)[]; result = emitter.eventNames(); } diff --git a/node/node.d.ts b/node/node.d.ts index 888da5cec4..7f228e1765 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -241,20 +241,20 @@ declare namespace NodeJS { } export class EventEmitter { - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; + addListener(event: string|symbol, listener: Function): this; + on(event: string|symbol, listener: Function): this; + once(event: string|symbol, listener: Function): this; + removeListener(event: string|symbol, listener: Function): this; + removeAllListeners(event?: string|symbol): this; setMaxListeners(n: number): this; getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - listenerCount(type: string): number; + listeners(event: string|symbol): Function[]; + emit(event: string|symbol, ...args: any[]): boolean; + listenerCount(type: string|symbol): number; // Added in Node 6... - prependListener(event: string, listener: Function): this; - prependOnceListener(event: string, listener: Function): this; - eventNames(): string[]; + prependListener(event: string|symbol, listener: Function): this; + prependOnceListener(event: string|symbol, listener: Function): this; + eventNames(): (string|symbol)[]; } export interface ReadableStream extends EventEmitter { @@ -549,22 +549,22 @@ declare module "querystring" { declare module "events" { export class EventEmitter extends NodeJS.EventEmitter { static EventEmitter: EventEmitter; - static listenerCount(emitter: EventEmitter, event: string): number; // deprecated + static listenerCount(emitter: EventEmitter, event: string|symbol): number; // deprecated static defaultMaxListeners: number; - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - prependListener(event: string, listener: Function): this; - prependOnceListener(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; + addListener(event: string|symbol, listener: Function): this; + on(event: string|symbol, listener: Function): this; + once(event: string|symbol, listener: Function): this; + prependListener(event: string|symbol, listener: Function): this; + prependOnceListener(event: string|symbol, listener: Function): this; + removeListener(event: string|symbol, listener: Function): this; + removeAllListeners(event?: string|symbol): this; setMaxListeners(n: number): this; getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - eventNames(): string[]; - listenerCount(type: string): number; + listeners(event: string|symbol): Function[]; + emit(event: string|symbol, ...args: any[]): boolean; + eventNames(): (string|symbol)[]; + listenerCount(type: string|symbol): number; } } From a982c80d5537adbb10e61630436b6f33970c180c Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:45:34 +0300 Subject: [PATCH 584/844] Delete index.d.ts --- react-redux-toastr/index.d.ts | 105 ---------------------------------- 1 file changed, 105 deletions(-) delete mode 100644 react-redux-toastr/index.d.ts diff --git a/react-redux-toastr/index.d.ts b/react-redux-toastr/index.d.ts deleted file mode 100644 index fb3dabfa61..0000000000 --- a/react-redux-toastr/index.d.ts +++ /dev/null @@ -1,105 +0,0 @@ -// Type definitions for react-redux-toastr 3.7.0 -// Project: https://github.com/diegoddox/react-redux-toastr -// Definitions by: Aleksandar Ivanov https://github.com/Smiche -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "react-redux-toastr" { - import R = __React; - import _Redux = Redux; - - interface ToastrOptions { - /** - * Timeout in miliseconds. - */ - timeOut?: number, - /** - * Show newest on top or bottom. - */ - newestOnTop?: boolean, - /** - * Position of the toastr: top-left, top-center, top-right, bottom-left, bottom-center and bottom-right - */ - position?: string, - confirmText?: ConfirmText - } - - interface ConfirmText { - okText: string, - cancelText: string - } - - /** - * Toastr react component. - */ - export default class ReduxToastr extends R.Component{ } - - interface EmitterOptions { - /** - * Notification popup icon. - * icon-close-round, icon-information-circle, icon-check-1, icon-exclamation-triangle, icon-exclamation-alert - */ - icon?: string, - /** - * Timeout in miliseconds. - */ - timeOut?: number, - removeOnHover?: boolean, - removeOnClick?: boolean, - component?: R.Component, - onShowComplete?: () => void, - onHideComplete?: () => void - } - - interface ToastrConfirmOptions { - onOk: () => void, - onCancel: () => void - } - - interface ToastrEmitter { - /** - * Used to provide a large amount of information. - * It will not close unless a timeOut is provided. - */ - message: (title: string, message: string, options?: EmitterOptions) => void, - info: (title: string, message: string, options?: EmitterOptions) => void, - success: (title: string, message: string, options?: EmitterOptions) => void, - warning: (title: string, message: string, options?: EmitterOptions) => void, - error: (title: string, message: string, options?: EmitterOptions) => void, - /** - * Clear all notifications - */ - clean: () => void, - /** - * Hook confirmation toastr with callback. - */ - confirm: (message: string, options: ToastrConfirmOptions) => any - } - - /** - * Possible actions to dispatch. - */ - interface Actions { - addToastrAction: Redux.Action, - clean: Redux.Action, - remove: Redux.Action, - success: Redux.Action, - info: Redux.Action, - warning: Redux.Action, - error: Redux.Action, - showConfirm: Redux.Action, - hideConfirm: Redux.Action - } - - /** - * Action creator for toastr. - */ - export var actions: Redux.ActionCreator; - /** - * Reducer for the toastr state. - * Combine with your reducers. - */ - export var reducer: Redux.Reducer; - /** - * Used to issue toastr notifications. - */ - export var toastr: ToastrEmitter; -} From 02935de0ccd7821fcbea1e5b091f13b29d7df5f2 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:46:14 +0300 Subject: [PATCH 585/844] Update library-tests.ts --- react-redux-toastr/library-tests.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/react-redux-toastr/library-tests.ts b/react-redux-toastr/library-tests.ts index 427823b7c1..3abfc668d4 100644 --- a/react-redux-toastr/library-tests.ts +++ b/react-redux-toastr/library-tests.ts @@ -1,7 +1,7 @@ -/// -/// -/// -/// +/// +/// +/// +/// import {toastr, reducer as toastrReducer, actions} from 'react-redux-toastr'; import ReduxToastr from 'react-redux-toastr'; import * as React from 'react'; From 2837bdcd4b3e0ed0a326a6c28215709c345498a4 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:46:40 +0300 Subject: [PATCH 586/844] Rename library-tests.ts to react-redux-toastr-tests.ts --- .../{library-tests.ts => react-redux-toastr-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename react-redux-toastr/{library-tests.ts => react-redux-toastr-tests.ts} (100%) diff --git a/react-redux-toastr/library-tests.ts b/react-redux-toastr/react-redux-toastr-tests.ts similarity index 100% rename from react-redux-toastr/library-tests.ts rename to react-redux-toastr/react-redux-toastr-tests.ts From 18780a108d295a2a41ab690bc5747c33d9131931 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:47:05 +0300 Subject: [PATCH 587/844] Create react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 108 +++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 react-redux-toastr/react-redux-toastr.d.ts diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts new file mode 100644 index 0000000000..b10d430065 --- /dev/null +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -0,0 +1,108 @@ +// Type definitions for react-redux-toastr 3.7.0 +// Project: https://github.com/diegoddox/react-redux-toastr +// Definitions by: Aleksandar Ivanov https://github.com/Smiche +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +declare module "react-redux-toastr" { + import R = __React; + import _Redux = Redux; + + interface ToastrOptions { + /** + * Timeout in miliseconds. + */ + timeOut?: number, + /** + * Show newest on top or bottom. + */ + newestOnTop?: boolean, + /** + * Position of the toastr: top-left, top-center, top-right, bottom-left, bottom-center and bottom-right + */ + position?: string, + confirmText?: ConfirmText + } + + interface ConfirmText { + okText: string, + cancelText: string + } + + /** + * Toastr react component. + */ + export default class ReduxToastr extends R.Component{ } + + interface EmitterOptions { + /** + * Notification popup icon. + * icon-close-round, icon-information-circle, icon-check-1, icon-exclamation-triangle, icon-exclamation-alert + */ + icon?: string, + /** + * Timeout in miliseconds. + */ + timeOut?: number, + removeOnHover?: boolean, + removeOnClick?: boolean, + component?: R.Component, + onShowComplete?: () => void, + onHideComplete?: () => void + } + + interface ToastrConfirmOptions { + onOk: () => void, + onCancel: () => void + } + + interface ToastrEmitter { + /** + * Used to provide a large amount of information. + * It will not close unless a timeOut is provided. + */ + message: (title: string, message: string, options?: EmitterOptions) => void, + info: (title: string, message: string, options?: EmitterOptions) => void, + success: (title: string, message: string, options?: EmitterOptions) => void, + warning: (title: string, message: string, options?: EmitterOptions) => void, + error: (title: string, message: string, options?: EmitterOptions) => void, + /** + * Clear all notifications + */ + clean: () => void, + /** + * Hook confirmation toastr with callback. + */ + confirm: (message: string, options: ToastrConfirmOptions) => any + } + + /** + * Possible actions to dispatch. + */ + interface Actions { + addToastrAction: Redux.Action, + clean: Redux.Action, + remove: Redux.Action, + success: Redux.Action, + info: Redux.Action, + warning: Redux.Action, + error: Redux.Action, + showConfirm: Redux.Action, + hideConfirm: Redux.Action + } + + /** + * Action creator for toastr. + */ + export var actions: Redux.ActionCreator; + /** + * Reducer for the toastr state. + * Combine with your reducers. + */ + export var reducer: Redux.Reducer; + /** + * Used to issue toastr notifications. + */ + export var toastr: ToastrEmitter; +} From e6e922c65ae7c97eee8adcb36acd1e9bcaae189d Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:55:37 +0300 Subject: [PATCH 588/844] Update react-redux-toastr-tests.ts --- .../react-redux-toastr-tests.ts | 25 +------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/react-redux-toastr/react-redux-toastr-tests.ts b/react-redux-toastr/react-redux-toastr-tests.ts index 3abfc668d4..bd0426face 100644 --- a/react-redux-toastr/react-redux-toastr-tests.ts +++ b/react-redux-toastr/react-redux-toastr-tests.ts @@ -1,6 +1,6 @@ /// /// -/// +/// /// import {toastr, reducer as toastrReducer, actions} from 'react-redux-toastr'; import ReduxToastr from 'react-redux-toastr'; @@ -16,29 +16,6 @@ function test() { var providerFactory = React.createFactory(Provider); var root = providerFactory({ store: store }, element); - class Test extends React.Component{ - private toastr; - constructor() { - super() - this.toastr = bindActionCreators(actions, this.props.dispatch); - this.toastr.clean(); - this.toastr.success("hi"); - } - - } - - - var TestComponent = connect(mapStateToProps, mapDispatchToProps)(Test); - function mapDispatchToProps(dispatch) { - return { - actions: bindActionCreators(actions, dispatch) - }; - } - - function mapStateToProps(state) { - return {}; - } - function callback() { } toastr.clean(); From 42e0076772967425975dc40fcec076b7c06e1d9d Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:58:24 +0300 Subject: [PATCH 589/844] Update react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts index b10d430065..cef006ab20 100644 --- a/react-redux-toastr/react-redux-toastr.d.ts +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-redux-toastr 3.7.0 // Project: https://github.com/diegoddox/react-redux-toastr -// Definitions by: Aleksandar Ivanov https://github.com/Smiche +// Definitions by: Aleksandar Ivanov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// From 0502f8480e068fafd516a1189f0ce25a26abb387 Mon Sep 17 00:00:00 2001 From: David Poetzsch-Heffter Date: Tue, 20 Sep 2016 16:44:20 +0200 Subject: [PATCH 590/844] added import statement --- parse-mockdb/parse-mockdb-tests.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/parse-mockdb/parse-mockdb-tests.ts b/parse-mockdb/parse-mockdb-tests.ts index 89f586d9e8..8d60573a8b 100644 --- a/parse-mockdb/parse-mockdb-tests.ts +++ b/parse-mockdb/parse-mockdb-tests.ts @@ -1,5 +1,7 @@ /// +import * as ParseMockDB from "parse-mockdb"; + ParseMockDB.mockDB(); // Mock the Parse RESTController // from parse-mockdb test suite From 962044d3ceb599d00c6ec69053218439b0df87cb Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Tue, 20 Sep 2016 10:46:08 -0400 Subject: [PATCH 591/844] Capitalize WebhookOptions --- twilio/twilio.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index c0f16211f5..824b596330 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -429,7 +429,7 @@ declare namespace twilio { export class TwimlResponse extends Node {} /// webhook.js - export interface webhookOptions { + export interface WebhookOptions { validate?: boolean; includeHelpers?: boolean; host?: string; @@ -450,8 +450,8 @@ declare namespace twilio { // For interop with node middleware chains export interface MiddlewareFunction { (request: Http.ServerRequest, response: Http.ServerResponse, next: Express.NextFunction): void; } - export function webhook(authToken: string, options?: webhookOptions): MiddlewareFunction; - export function webhook(options?: webhookOptions): MiddlewareFunction; + export function webhook(authToken: string, options?: WebhookOptions): MiddlewareFunction; + export function webhook(options?: 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; From be207d84a7df0bd0e3047fd60e447996ab707b04 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 18:03:49 +0300 Subject: [PATCH 592/844] Update react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts index cef006ab20..380dd3ad61 100644 --- a/react-redux-toastr/react-redux-toastr.d.ts +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -48,13 +48,13 @@ declare module "react-redux-toastr" { removeOnHover?: boolean, removeOnClick?: boolean, component?: R.Component, - onShowComplete?: () => void, - onHideComplete?: () => void + onShowComplete?: (): void; + onHideComplete?: (): void; } interface ToastrConfirmOptions { - onOk: () => void, - onCancel: () => void + onOk: (): void; + onCancel: (): void; } interface ToastrEmitter { @@ -62,19 +62,19 @@ declare module "react-redux-toastr" { * Used to provide a large amount of information. * It will not close unless a timeOut is provided. */ - message: (title: string, message: string, options?: EmitterOptions) => void, - info: (title: string, message: string, options?: EmitterOptions) => void, - success: (title: string, message: string, options?: EmitterOptions) => void, - warning: (title: string, message: string, options?: EmitterOptions) => void, - error: (title: string, message: string, options?: EmitterOptions) => void, + message: (title: string, message: string, options?: EmitterOptions): void; + info: (title: string, message: string, options?: EmitterOptions): void; + success: (title: string, message: string, options?: EmitterOptions): void; + warning: (title: string, message: string, options?: EmitterOptions): void; + error: (title: string, message: string, options?: EmitterOptions): void; /** * Clear all notifications */ - clean: () => void, + clean: (): void; /** * Hook confirmation toastr with callback. */ - confirm: (message: string, options: ToastrConfirmOptions) => any + confirm: (message: string, options: ToastrConfirmOptions): void; } /** From 913827f4c26e487db4454299e65f685f19ac6ced Mon Sep 17 00:00:00 2001 From: Aleksey Blokhin Date: Tue, 20 Sep 2016 18:14:10 +0300 Subject: [PATCH 593/844] `finally` returns original promise. --- js-data/js-data.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js-data/js-data.d.ts b/js-data/js-data.d.ts index 58bef671b1..284e66486b 100644 --- a/js-data/js-data.d.ts +++ b/js-data/js-data.d.ts @@ -15,7 +15,7 @@ declare namespace JSData { catch(onRejected?:(error:any) => U | JSDataPromise): JSDataPromise; // enhanced with finally - finally(finallyCb?:() => U):JSDataPromise; + finally(finallyCb?:() => any): JSDataPromise; } interface DSConfiguration extends IDSResourceLifecycleEventHandlers { From f11138f44326f40a9c676758ef2bf0164fa94a41 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 18:15:54 +0300 Subject: [PATCH 594/844] Update react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts index 380dd3ad61..21c72e093a 100644 --- a/react-redux-toastr/react-redux-toastr.d.ts +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -48,8 +48,8 @@ declare module "react-redux-toastr" { removeOnHover?: boolean, removeOnClick?: boolean, component?: R.Component, - onShowComplete?: (): void; - onHideComplete?: (): void; + onShowComplete?(): void; + onHideComplete?(): void; } interface ToastrConfirmOptions { @@ -62,19 +62,19 @@ declare module "react-redux-toastr" { * Used to provide a large amount of information. * It will not close unless a timeOut is provided. */ - message: (title: string, message: string, options?: EmitterOptions): void; - info: (title: string, message: string, options?: EmitterOptions): void; - success: (title: string, message: string, options?: EmitterOptions): void; - warning: (title: string, message: string, options?: EmitterOptions): void; - error: (title: string, message: string, options?: EmitterOptions): void; + message(title: string, message: string, options?: EmitterOptions): void; + info(title: string, message: string, options?: EmitterOptions): void; + success(title: string, message: string, options?: EmitterOptions): void; + warning(title: string, message: string, options?: EmitterOptions): void; + error(title: string, message: string, options?: EmitterOptions): void; /** * Clear all notifications */ - clean: (): void; + clean(): void; /** * Hook confirmation toastr with callback. */ - confirm: (message: string, options: ToastrConfirmOptions): void; + confirm(message: string, options: ToastrConfirmOptions): void; } /** From 41e5e3d1782f6ded0a0bfdc22f2032550c966ca3 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 18:16:27 +0300 Subject: [PATCH 595/844] Update react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts index 21c72e093a..1b628455aa 100644 --- a/react-redux-toastr/react-redux-toastr.d.ts +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -53,8 +53,8 @@ declare module "react-redux-toastr" { } interface ToastrConfirmOptions { - onOk: (): void; - onCancel: (): void; + onOk(): void; + onCancel(): void; } interface ToastrEmitter { From 19425cf32716e63bbbce6a091ec83eaf81a1a3ca Mon Sep 17 00:00:00 2001 From: "Boland, Craig" Date: Tue, 20 Sep 2016 12:22:11 -0500 Subject: [PATCH 596/844] Updated jquery.dataTables.d.ts for 1.10.6. Version release notes: https://cdn.datatables.net/1.10.6/ * Added rows().every() * Added columns().every() * Added cells().every() * Added init() * Expanded method signature when ajax.data is used as a function. --- jquery.dataTables/jquery.dataTables-tests.ts | 196 ++++++++++--------- jquery.dataTables/jquery.dataTables.d.ts | 58 ++++-- 2 files changed, 147 insertions(+), 107 deletions(-) diff --git a/jquery.dataTables/jquery.dataTables-tests.ts b/jquery.dataTables/jquery.dataTables-tests.ts index 4d1d114cb4..6329861604 100644 --- a/jquery.dataTables/jquery.dataTables-tests.ts +++ b/jquery.dataTables/jquery.dataTables-tests.ts @@ -82,21 +82,21 @@ $(document).ready(function () { width: "200px" } col = - { - data: "", - orderData: [10, 11, 20], - render: "", - } + { + data: "", + orderData: [10, 11, 20], + render: "", + } col = - { - data: colDataObject, - render: colRenderObject, - } + { + data: colDataObject, + render: colRenderObject, + } col = - { - data: colDataFunc, - render: colRenderFunc, - } + { + data: colDataFunc, + render: colRenderFunc, + } //#endregion "Column" @@ -124,16 +124,16 @@ $(document).ready(function () { }; colDef = - { - targets: "2", - cellType: "th", - }; + { + targets: "2", + cellType: "th", + }; colDef = - { - targets: ["2", 5], - cellType: "th", - }; + { + targets: ["2", 5], + cellType: "th", + }; //#endregion "ColumnDef" @@ -159,7 +159,7 @@ $(document).ready(function () { var ajaxFunc: DataTables.FunctionAjax = function (data, callback, settings) { }; - var ajaxDataFunc: DataTables.FunctionAjaxData = function (data) { + var ajaxDataFunc: DataTables.FunctionAjaxData = function (data, settings) { return data; }; @@ -229,41 +229,41 @@ $(document).ready(function () { config = - { - ajax: ajaxFunc, - deferLoading: [10, 100], - lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], - order: [0, 'asc'], - orderFixed: [[0, 'asc'], [1, 'asc']], - renderer: { - header: "bootstrap", - pageButton: "jqueryui" - }, - search: { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, - searchCols: [ - null, - { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, - { "search": "" }, - { "search": "", "smart": true }, - null - ], - }; + { + ajax: ajaxFunc, + deferLoading: [10, 100], + lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], + order: [0, 'asc'], + orderFixed: [[0, 'asc'], [1, 'asc']], + renderer: { + header: "bootstrap", + pageButton: "jqueryui" + }, + search: { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, + searchCols: [ + null, + { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, + { "search": "" }, + { "search": "", "smart": true }, + null + ], + }; config = - { - ajax: { - data: {}, - dataSrc: "", - }, - }; + { + ajax: { + data: {}, + dataSrc: "", + }, + }; config = - { - ajax: { - data: ajaxDataFunc, - dataSrc: function (data) { }, - }, - }; + { + ajax: { + data: ajaxDataFunc, + dataSrc: function (data) { }, + }, + }; //#endregion "Settings" @@ -309,6 +309,8 @@ $(document).ready(function () { draw = dt.draw(true); draw.$(""); + var initSettings = dt.init(); + var off = dt.off("event"); off = dt.off("event", function () { }); off.$(""); @@ -385,11 +387,11 @@ $(document).ready(function () { var select = $('`-, + * `