From 4e00b9e8dc11eef0b7ef4bd2f1bbfb91f3e2cc2f Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Thu, 12 May 2016 22:24:49 +0100 Subject: [PATCH 001/564] Update to version 2.20.4 Update methods from node-validator (https://github.com/chriso/validator.js) and update express-validator methods to adhere to the latest api. --- express-validator/express-validator-tests.ts | 14 +- express-validator/express-validator.d.ts | 136 ++++++++++++------- 2 files changed, 99 insertions(+), 51 deletions(-) diff --git a/express-validator/express-validator-tests.ts b/express-validator/express-validator-tests.ts index 74bd277e46..ebd61d6cfc 100644 --- a/express-validator/express-validator-tests.ts +++ b/express-validator/express-validator-tests.ts @@ -15,19 +15,23 @@ app.post('/:urlparam', function(req: express.Request, res: express.Response) { // Similarly checkParams only checks in req.params (URL params) and // checkQuery only checks req.query (GET params). req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt(); - req.checkParams('urlparam', 'Invalid urlparam').isAlpha(); + req.checkParams('urlparam', 'Invalid urlparam').isAlpha().matches(/test?/i).matches('test?', 'i'); req.checkQuery('getparam', 'Invalid getparam').isInt(); - req.checkHeader('testHeader', 'Invalid testHeader').isLowercase().isUppercase(); - req.checkFiles('testFiles', 'Invalid testFiles').isUrl(); - + req.checkHeaders('testHeader', 'Invalid testHeader').isLowercase().isUppercase(); + req.checkFiles('testFiles', 'Invalid testFiles').isURL(); // OR assert can be used to check on all 3 types of params. // req.assert('postparam', 'Invalid postparam').notEmpty().isInt(); // req.assert('urlparam', 'Invalid urlparam').isAlpha(); // req.assert('getparam', 'Invalid getparam').isInt(); - req.sanitize('postparam').toBoolean(); req.filter('postparam').toBoolean(); + req.sanitize('postparam').blacklist('t').blacklist(['']).whitelist('hello').whitelist(['h', 'e', 'l']); + req.sanitizeBody('postvar').trim().stripLow().escape(); + req.sanitizeQuery('queryvar').toDate(); + req.sanitizeParams('urlparam').toFloat().toInt().toInt(10); + req.sanitizeHeaders('header').normalizeEmail(); + var errors = req.validationErrors(); var mappedErrors = req.validationErrors(true); diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index 52792a391f..cb15aebf8f 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -1,9 +1,10 @@ -// Type definitions for express-validator 2.9.0 +// Type definitions for express-validator 2.20.4 // Project: https://github.com/ctavan/express-validator -// Definitions by: Nathan Ridley , Jonathan Häberle +// Definitions by: Nathan Ridley , Jonathan Häberle , Peter Harris // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// // Add RequestValidation Interface on to Express's Request Interface. declare namespace Express { @@ -31,25 +32,33 @@ declare namespace ExpressValidator { param: string; } - interface ValidatorFunction { (item: string, message: string): Validator; } + interface ValidatorFunction { (item: string | {}, message?: string): Validator; } + interface ValidatorExtraFunction extends ValidatorFunction { (matchIndex: number, message?: string): Validator; }; interface SanitizerFunction { (item: string): Sanitizer; } interface Dictionary { [key: string]: T; } export interface RequestValidation { - assert: ValidatorFunction; - check: ValidatorFunction; + assert: ValidatorExtraFunction; + validate: ValidatorExtraFunction; + check: ValidatorExtraFunction; checkBody: ValidatorFunction; checkFiles: ValidatorFunction; - checkHeader: ValidatorFunction; + checkHeaders: ValidatorFunction; checkParams: ValidatorFunction; checkQuery: ValidatorFunction; - validate: ValidatorFunction; - + filter: SanitizerFunction; sanitize: SanitizerFunction; - + sanitizeBody: SanitizerFunction; + sanitizeQuery: SanitizerFunction; + sanitizeParams: SanitizerFunction; + sanitizeHeaders: SanitizerFunction; + onValidationError(errback: (msg: string) => void): void; - validationErrors(mapped?: boolean): Dictionary | any[]; + validationErrors(mapped?: boolean): Dictionary | MappedError[]; + validationErrors(mapped?: boolean): Dictionary | T[]; + asyncValidationErrors(mapped?: boolean): Promise>; + asyncValidationErrors(mapped?: boolean): Promise>; } export interface Validator { @@ -61,12 +70,13 @@ declare namespace ExpressValidator { * Alias for notRegex() */ not(): Validator; - isEmail(): Validator; + isEmail(options?:{}): Validator; /** * Accepts http, https, ftp */ - isUrl(): Validator; - + isURL(): Validator; + isFQDN(options?: MinMaxOptions): Validator; + /** * Combines isIPv4 and isIPv6 */ @@ -74,8 +84,21 @@ declare namespace ExpressValidator { isIPv4(): Validator; isIPv6(): Validator; isMACAddress(): Validator; - isAlpha(): Validator; - isAlphanumeric(): Validator; + isISBN(version?: number): Validator; + isISIN(): Validator; + isISO8601(): Validator; + isMobilePhone(locale: string): Validator; + isMongoId(): Validator; + isMultibyte(): Validator; + isAlpha(locale?: string): Validator; + isAlphanumeric(locale?: string): Validator; + isAscii(): Validator; + isBase64(): Validator; + isBoolean(): Validator; + isByteLength(options: MinMaxOptions): Validator; + isCurrency(options: {}): Validator; + isDataURI(): Validator; + isDivisibleBy(num: number): Validator; isNumeric(): Validator; isHexadecimal(): Validator; /** @@ -85,7 +108,7 @@ declare namespace ExpressValidator { /** * isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't */ - isInt(): Validator; + isInt(options?: MinMaxOptions): Validator; isLowercase(): Validator; isUppercase(): Validator; isDecimal(): Validator; @@ -93,10 +116,13 @@ declare namespace ExpressValidator { * Alias for isDecimal */ isFloat(): Validator; + isFullWidth(): Validator; + isHalfWidth(): Validator; + isVariableWidth(): Validator; /** * Check if length is 0 */ - notNull(): Validator; + //notNull(): Validator; // I don't see this in the documentation or code anywhere. isNull(): Validator; /** * Not just whitespace (input.trim().length !== 0) @@ -104,12 +130,14 @@ declare namespace ExpressValidator { notEmpty(): Validator; equals(equals:any): Validator; contains(str:string): Validator; - notContains(str:string): Validator; + //notContains(str:string): Validator; // I don't see this in the documentation or code anywhere. + matches(pattern:string, modifiers?:string): Validator; + matches(pattern: RegExp): Validator; /** * Usage: regex(/[a-z]/i) or regex('[a-z]','i') */ - regex(pattern:string, modifiers:string): Validator; - notRegex(pattern:string, modifiers:string): Validator; + //regex(pattern:string, modifiers:string): Validator; // I don't see this in the documentation or code anywhere. + //notRegex(pattern:string, modifiers:string): Validator; // I don't see this in the documentation or code anywhere. /** * max is optional */ @@ -117,7 +145,7 @@ declare namespace ExpressValidator { /** * Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier */ - isUUID(version:number): Validator; + isUUID(version?:number): Validator; /** * Alias for isUUID(3) */ @@ -137,17 +165,20 @@ declare namespace ExpressValidator { /** * Argument is optional and defaults to today. Comparison is non-inclusive */ - isAfter(date:Date): Validator; + isAfter(date?:Date): Validator; /** * Argument is optional and defaults to today. Comparison is non-inclusive */ - isBefore(date:Date): Validator; + isBefore(date?:Date): Validator; isIn(options:string): Validator; isIn(options:string[]): Validator; notIn(options:string): Validator; notIn(options:string[]): Validator; max(val:string): Validator; min(val:string): Validator; + isJSON(): Validator; + isLength(options: MinMaxOptions): Validator; + isWhitelisted(chars: string); /** * Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats */ @@ -155,7 +186,10 @@ declare namespace ExpressValidator { /** * Check an input only when the input exists */ - optional(): Validator; + isSurrogatePar(): Validator; + + optional(options?: { checkFalsy?: boolean }): Validator; + withMessage(message: string): Validator; } interface Sanitizer { @@ -165,40 +199,50 @@ declare namespace ExpressValidator { trim(...chars:string[]): Sanitizer; ltrim(...chars:string[]): Sanitizer; rtrim(...chars:string[]): Sanitizer; - ifNull(replace:any): Sanitizer; + stripLow(keep_new_lines?: boolean): Sanitizer; + //ifNull(replace:any): Sanitizer; // I don't see this in the documentation or code anywhere. toFloat(): Sanitizer; - toInt(): Sanitizer; + toInt(radix?: number): Sanitizer; /** - * True unless str = '0', 'false', or str.length == 0 - */ - toBoolean(): Sanitizer; - /** - * False unless str = '1' or 'true' - */ - toBooleanStrict(): Sanitizer; - /** - * Decode HTML entities + * True unless str = '0', 'false', or str.length == 0. In strict mode only '1' and 'true' return true. */ + toBoolean(strict?: boolean): Sanitizer; /** - * Convert the input string to a date, or null if the input is not a date. - */ - toDate(): Sanitizer; - - entityDecode(): Sanitizer; - entityEncode(): Sanitizer; + * Convert the input string to a date, or null if the input is not a date. + */ + toDate(): Sanitizer; + /** * Escape &, <, >, and " */ escape(): Sanitizer; + /** - * Remove common XSS attack vectors from user-supplied HTML + * Replaces HTML encoded entities with <, >, &, ', " and /. */ - xss(): Sanitizer; + unescape(): Sanitizer; + + blacklist(chars: string): Sanitizer; + blacklist(chars: string[]): Sanitizer; + whitelist(chars: string): Sanitizer; + whitelist(chars: string[]): Sanitizer; + + normalizeEmail(options?: { lowercase?: boolean; remove_dots?: boolean; remove_extensions?: boolean }): Sanitizer; + /** - * Remove common XSS attack vectors from images + * !!! XSS sanitization was removed from the library (see: https://github.com/chriso/validator.js#xss-sanitization) */ - xss(fromImages:boolean): Sanitizer; } - + + interface MappedError { + param: string; + msg: string; + value: string; + } + + interface MinMaxOptions { + min?: number; + max?: number; + } } From 396e37eb8b17cace44ba2bce0f2aa59a88d17fd0 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Thu, 12 May 2016 22:38:26 +0100 Subject: [PATCH 002/564] Remove ambient semicolon --- express-validator/express-validator.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index cb15aebf8f..583ffbf6e8 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -33,7 +33,7 @@ declare namespace ExpressValidator { } interface ValidatorFunction { (item: string | {}, message?: string): Validator; } - interface ValidatorExtraFunction extends ValidatorFunction { (matchIndex: number, message?: string): Validator; }; + interface ValidatorExtraFunction extends ValidatorFunction { (matchIndex: number, message?: string): Validator; } interface SanitizerFunction { (item: string): Sanitizer; } interface Dictionary { [key: string]: T; } From 10bc473fe57df9c5acb2926faf785ece99beb37f Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Thu, 12 May 2016 22:44:39 +0100 Subject: [PATCH 003/564] Add return type to isWhitelisted method. --- express-validator/express-validator.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index 583ffbf6e8..71797efce2 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -178,7 +178,7 @@ declare namespace ExpressValidator { min(val:string): Validator; isJSON(): Validator; isLength(options: MinMaxOptions): Validator; - isWhitelisted(chars: string); + isWhitelisted(chars: string): Validator; /** * Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats */ From c59c139444477fda75df8541cd8c7bcb5c93ec5b Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Sun, 22 May 2016 13:16:47 +0200 Subject: [PATCH 004/564] 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 005/564] 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 006/564] 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 007/564] 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 008/564] 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 009/564] 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 010/564] 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 c8d5f64ef86cd7c3227bef1d412c034db8bbaf6d Mon Sep 17 00:00:00 2001 From: Gayan Ranasinghe Date: Mon, 4 Jul 2016 16:20:28 +0530 Subject: [PATCH 011/564] added some fields --- kendo-ui/kendo-ui.d.ts | 1425 ++++++++++++++++++++-------------------- 1 file changed, 717 insertions(+), 708 deletions(-) diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index 934a8cd8b1..b8aea8a61a 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -3,7 +3,7 @@ // Definitions by: Telerik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// + declare namespace kendo { function culture(): { @@ -89,40 +89,10 @@ declare namespace kendo { }; }; - var cultures: {[culture: string] : { - name?: string; - calendar?: { - AM: string[]; - PM: string[]; - days: { - names: string[]; - namesAbbr: string[]; - namesShort: string[]; - firstDay: number; - }; - months: { - names: string[]; - namesAbbr: string[]; - }; - patterns: { - D: string; - F: string; - G: string; - M: string; - T: string; - Y: string; - d: string; - g: string; - m: string; - s: string; - t: string; - u: string; - y: string; - }; - twoDigitYearMax: number; - }; - calendars?: { - standard: { + var cultures: { + [culture: string]: { + name?: string; + calendar?: { AM: string[]; PM: string[]; days: { @@ -152,25 +122,57 @@ declare namespace kendo { }; twoDigitYearMax: number; }; - }; - numberFormat?: { - currency: { + calendars?: { + standard: { + AM: string[]; + PM: string[]; + days: { + names: string[]; + namesAbbr: string[]; + namesShort: string[]; + firstDay: number; + }; + months: { + names: string[]; + namesAbbr: string[]; + }; + patterns: { + D: string; + F: string; + G: string; + M: string; + T: string; + Y: string; + d: string; + g: string; + m: string; + s: string; + t: string; + u: string; + y: string; + }; + twoDigitYearMax: number; + }; + }; + numberFormat?: { + currency: { + decimals: number; + groupSize: number[]; + pattern: string[]; + symbol: string; + }; decimals: number; groupSize: number[]; pattern: string[]; - symbol: string; + percent: { + decimals: number; + groupSize: number[]; + pattern: string[]; + symbol: string; + }; }; - decimals: number; - groupSize: number[]; - pattern: string[]; - percent: { - decimals: number; - groupSize: number[]; - pattern: string[]; - symbol: string; - }; - }; - }}; + } + }; function format(format: string, ...values: any[]): string; @@ -300,7 +302,7 @@ declare namespace kendo { } class ViewContainer extends Observable { - view: View; + view: View; } class Layout extends View { @@ -488,8 +490,8 @@ declare namespace kendo.data { change(e: Object): void; start(source: kendo.Observable): void; stop(source: kendo.Observable): void; - get (): any; - set (value: any): void; + get(): any; + set(value: any): void; destroy(): void; } @@ -500,7 +502,7 @@ declare namespace kendo.data { } class EventBinding extends Binding { - get (): void; + get(): void; } class TemplateBinding extends Binding { @@ -508,7 +510,8 @@ declare namespace kendo.data { render(value: Object): string; } - namespace binders { } + module binders { } + export var binders; interface Bindings { [key: string]: Binding; @@ -531,7 +534,7 @@ declare namespace kendo.data { interface BinderOptions { } - class ObservableObject extends Observable{ + class ObservableObject extends Observable { constructor(value?: any); uid: string; init(value?: any): void; @@ -571,6 +574,8 @@ declare namespace kendo.data { isAllDay?: boolean; id?: any; start?: Date; + ownerId?: number; + taskId?: number; startTimezone?: string; recurrenceId?: any; recurrenceRule?: string; @@ -583,7 +588,8 @@ declare namespace kendo.data { static fields: DataSourceSchemaModelFields; constructor(data?: SchedulerEventData); - + ownerId: number; + taskId: number; description: string; end: Date; endTimezone: string; @@ -839,7 +845,7 @@ declare namespace kendo.data { columns: PivotSchemaColumnAxis; } - interface PivotSchema extends DataSourceSchema{ + interface PivotSchema extends DataSourceSchema { axes?: any; catalogs?: any; cubes?: any; @@ -948,7 +954,7 @@ declare namespace kendo.data { } interface DataSourceSchemaWithConstructorModel extends DataSourceSchema { - model?: typeof Model; + model?: typeof Model; } interface DataSourceSchemaModel { @@ -996,7 +1002,7 @@ declare namespace kendo.data { every(callback: (item: Object, index: number, source: ObservableArray) => boolean): boolean; filter(callback: (item: Object, index: number, source: ObservableArray) => boolean): any[]; find(callback: (item: Object, index: number, source: ObservableArray) => boolean): any; - forEach(callback: (item: Object, index: number, source: ObservableArray) => void ): void; + forEach(callback: (item: Object, index: number, source: ObservableArray) => void): void; indexOf(item: any): number; join(separator: string): string; map(callback: (item: Object, index: number, source: ObservableArray) => any): any[]; @@ -1022,7 +1028,7 @@ declare namespace kendo.data { items?: kendo.data.Model[]; } - class DataSource extends Observable{ + class DataSource extends Observable { options: DataSourceOptions; static create(options?: DataSourceOptions): DataSource; @@ -1242,7 +1248,7 @@ declare namespace kendo.data { sort?: any; transport?: DataSourceTransport; type?: string; - change? (e: DataSourceChangeEvent): void; + change?(e: DataSourceChangeEvent): void; error?(e: DataSourceErrorEvent): void; sync?(e: DataSourceEvent): void; requestStart?(e: DataSourceRequestStartEvent): void; @@ -1325,7 +1331,7 @@ declare namespace kendo.ui { function plugin(widget: typeof kendo.ui.Widget, register?: typeof kendo.dataviz.ui, prefix?: String): void; function plugin(widget: any, register?: typeof kendo.dataviz.ui, prefix?: String): void; - class Draggable extends kendo.ui.Widget{ + class Draggable extends kendo.ui.Widget { element: JQuery; currentTarget: JQuery; constructor(element: Element, options?: DraggableOptions); @@ -1336,7 +1342,7 @@ declare namespace kendo.ui { sender?: Draggable; } - class DropTarget extends kendo.ui.Widget{ + class DropTarget extends kendo.ui.Widget { element: JQuery; constructor(element: Element, options?: DropTargetOptions); options: DropTargetOptions; @@ -1366,7 +1372,7 @@ declare namespace kendo.ui { draggable?: kendo.ui.Draggable; } - class DropTargetArea extends kendo.ui.Widget{ + class DropTargetArea extends kendo.ui.Widget { element: JQuery; constructor(element: Element, options?: DropTargetAreaOptions); options: DropTargetAreaOptions; @@ -1517,7 +1523,7 @@ declare namespace kendo.dataviz.map.layer { declare namespace kendo.drawing.pdf { function saveAs(group: kendo.drawing.Group, fileName: string, - proxyUrl?: string, callback?: Function): void; + proxyUrl?: string, callback?: Function): void; } declare namespace kendo.geometry { @@ -1690,7 +1696,7 @@ declare namespace kendo.geometry { origin: kendo.geometry.Point; size: kendo.geometry.Size; - constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); + constructor(origin: kendo.geometry.Point | any, size: kendo.geometry.Size | any); static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; @@ -1916,7 +1922,7 @@ declare namespace kendo.drawing { } - interface FillOptions { + interface FillOptions { @@ -2215,7 +2221,7 @@ declare namespace kendo.drawing { } - interface PDFOptions { + interface PDFOptions { @@ -2319,7 +2325,7 @@ declare namespace kendo.drawing { interface RadialGradientOptions { name?: string; - center?: any|kendo.geometry.Point; + center?: any | kendo.geometry.Point; radius?: number; stops?: any; } @@ -2403,7 +2409,7 @@ declare namespace kendo.drawing { } - interface StrokeOptions { + interface StrokeOptions { @@ -2457,8 +2463,8 @@ declare namespace kendo.drawing { } interface SurfaceTooltip { - animation?: boolean|SurfaceTooltipAnimation; - appendTo?: string|JQuery; + animation?: boolean | SurfaceTooltipAnimation; + appendTo?: string | JQuery; } interface SurfaceOptions { @@ -2553,20 +2559,20 @@ declare namespace kendo.drawing { } - interface TooltipOptions { + interface TooltipOptions { autoHide?: boolean; - content?: string|Function; + content?: string | Function; position?: string; - height?: number|string; + height?: number | string; hideDelay?: number; offset?: number; shared?: boolean; showAfter?: number; showOn?: string; - width?: number|string; + width?: number | string; @@ -2636,14 +2642,14 @@ declare namespace kendo.ui { interface AutoCompleteOptions { name?: string; - animation?: boolean|AutoCompleteAnimation; - dataSource?: any|any|kendo.data.DataSource; + animation?: boolean | AutoCompleteAnimation; + dataSource?: any | any | kendo.data.DataSource; dataTextField?: string; delay?: number; enable?: boolean; filter?: string; - fixedGroupTemplate?: string|Function; - groupTemplate?: string|Function; + fixedGroupTemplate?: string | Function; + groupTemplate?: string | Function; height?: number; highlightFirst?: boolean; ignoreCase?: boolean; @@ -2652,10 +2658,11 @@ declare namespace kendo.ui { popup?: any; separator?: string; suggest?: boolean; - headerTemplate?: string|Function; - template?: string|Function; + value?: any; + headerTemplate?: string | Function; + template?: string | Function; valuePrimitive?: boolean; - virtual?: boolean|AutoCompleteVirtual; + virtual?: boolean | AutoCompleteVirtual; change?(e: AutoCompleteChangeEvent): void; close?(e: AutoCompleteCloseEvent): void; dataBound?(e: AutoCompleteDataBoundEvent): void; @@ -2773,8 +2780,8 @@ declare namespace kendo.ui { culture?: string; dates?: any; depth?: string; - disableDates?: any|Function; - footer?: string|Function; + disableDates?: any | Function; + footer?: string | Function; format?: string; max?: Date; min?: Date; @@ -2821,7 +2828,7 @@ declare namespace kendo.ui { interface ColorPaletteOptions { name?: string; - palette?: string|any; + palette?: string | any; columns?: number; tileSize?: ColorPaletteTileSize; value?: string; @@ -2876,7 +2883,7 @@ declare namespace kendo.ui { columns?: number; tileSize?: ColorPickerTileSize; messages?: ColorPickerMessages; - palette?: string|any; + palette?: string | any; opacity?: boolean; preview?: boolean; toolIcon?: string; @@ -2976,14 +2983,14 @@ declare namespace kendo.ui { autoBind?: boolean; cascadeFrom?: string; cascadeFromField?: string; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; dataTextField?: string; dataValueField?: string; delay?: number; enable?: boolean; filter?: string; - fixedGroupTemplate?: string|Function; - groupTemplate?: string|Function; + fixedGroupTemplate?: string | Function; + groupTemplate?: string | Function; height?: number; highlightFirst?: boolean; ignoreCase?: boolean; @@ -2992,12 +2999,12 @@ declare namespace kendo.ui { placeholder?: string; popup?: ComboBoxPopup; suggest?: boolean; - headerTemplate?: string|Function; - template?: string|Function; + headerTemplate?: string | Function; + template?: string | Function; text?: string; value?: string; valuePrimitive?: boolean; - virtual?: boolean|ComboBoxVirtual; + virtual?: boolean | ComboBoxVirtual; change?(e: ComboBoxChangeEvent): void; close?(e: ComboBoxCloseEvent): void; dataBound?(e: ComboBoxDataBoundEvent): void; @@ -3092,16 +3099,16 @@ declare namespace kendo.ui { interface ContextMenuOptions { name?: string; alignToAnchor?: boolean; - animation?: boolean|ContextMenuAnimation; + animation?: boolean | ContextMenuAnimation; closeOnClick?: boolean; - dataSource?: any|any; + dataSource?: any | any; direction?: string; filter?: string; hoverDelay?: number; orientation?: string; popupCollision?: string; showOn?: string; - target?: string|JQuery; + target?: string | JQuery; close?(e: ContextMenuCloseEvent): void; open?(e: ContextMenuOpenEvent): void; activate?(e: ContextMenuActivateEvent): void; @@ -3202,13 +3209,13 @@ declare namespace kendo.ui { interface DatePickerOptions { name?: string; - animation?: boolean|DatePickerAnimation; + animation?: boolean | DatePickerAnimation; ARIATemplate?: string; culture?: string; dates?: any; depth?: string; - disableDates?: any|Function; - footer?: string|Function; + disableDates?: any | Function; + footer?: string | Function; format?: string; max?: Date; min?: Date; @@ -3292,12 +3299,12 @@ declare namespace kendo.ui { interface DateTimePickerOptions { name?: string; - animation?: boolean|DateTimePickerAnimation; + animation?: boolean | DateTimePickerAnimation; ARIATemplate?: string; culture?: string; dates?: any; depth?: string; - disableDates?: any|Function; + disableDates?: any | Function; footer?: string; format?: string; interval?: number; @@ -3403,32 +3410,32 @@ declare namespace kendo.ui { interface DropDownListOptions { name?: string; - animation?: boolean|DropDownListAnimation; + animation?: boolean | DropDownListAnimation; autoBind?: boolean; cascadeFrom?: string; cascadeFromField?: string; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; dataTextField?: string; dataValueField?: string; delay?: number; enable?: boolean; filter?: string; - fixedGroupTemplate?: string|Function; - groupTemplate?: string|Function; + fixedGroupTemplate?: string | Function; + groupTemplate?: string | Function; height?: number; ignoreCase?: boolean; index?: number; minLength?: number; popup?: DropDownListPopup; - optionLabel?: string|any; - optionLabelTemplate?: string|Function; - headerTemplate?: string|Function; - template?: string|Function; - valueTemplate?: string|Function; + optionLabel?: string | any; + optionLabelTemplate?: string | Function; + headerTemplate?: string | Function; + template?: string | Function; + valueTemplate?: string | Function; text?: string; value?: string; valuePrimitive?: boolean; - virtual?: boolean|DropDownListVirtual; + virtual?: boolean | DropDownListVirtual; change?(e: DropDownListChangeEvent): void; close?(e: DropDownListCloseEvent): void; dataBound?(e: DropDownListDataBoundEvent): void; @@ -3550,32 +3557,32 @@ declare namespace kendo.ui { interface EditorFileBrowserTransportCreate { contentType?: string; - data?: any|string|Function; + data?: any | string | Function; dataType?: string; type?: string; - url?: string|Function; + url?: string | Function; } interface EditorFileBrowserTransportDestroy { contentType?: string; - data?: any|string|Function; + data?: any | string | Function; dataType?: string; type?: string; - url?: string|Function; + url?: string | Function; } interface EditorFileBrowserTransportRead { contentType?: string; - data?: any|string|Function; + data?: any | string | Function; dataType?: string; type?: string; - url?: string|Function; + url?: string | Function; } interface EditorFileBrowserTransport { read?: EditorFileBrowserTransportRead; uploadUrl?: string; - fileUrl?: string|Function; + fileUrl?: string | Function; destroy?: EditorFileBrowserTransportDestroy; create?: EditorFileBrowserTransportCreate; } @@ -3632,33 +3639,33 @@ declare namespace kendo.ui { interface EditorImageBrowserTransportCreate { contentType?: string; - data?: any|string|Function; + data?: any | string | Function; dataType?: string; type?: string; - url?: string|Function; + url?: string | Function; } interface EditorImageBrowserTransportDestroy { contentType?: string; - data?: any|string|Function; + data?: any | string | Function; dataType?: string; type?: string; - url?: string|Function; + url?: string | Function; } interface EditorImageBrowserTransportRead { contentType?: string; - data?: any|string|Function; + data?: any | string | Function; dataType?: string; type?: string; - url?: string|Function; + url?: string | Function; } interface EditorImageBrowserTransport { read?: EditorImageBrowserTransportRead; - thumbnailUrl?: string|Function; + thumbnailUrl?: string | Function; uploadUrl?: string; - imageUrl?: string|Function; + imageUrl?: string | Function; destroy?: EditorImageBrowserTransportDestroy; create?: EditorImageBrowserTransportCreate; } @@ -3747,15 +3754,15 @@ declare namespace kendo.ui { } interface EditorPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface EditorPdf { author?: string; - avoidLinks?: boolean|string; + avoidLinks?: boolean | string; creator?: string; date?: Date; fileName?: string; @@ -3763,7 +3770,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: EditorPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -3814,7 +3821,7 @@ declare namespace kendo.ui { messages?: EditorMessages; pasteCleanup?: EditorPasteCleanup; pdf?: EditorPdf; - resizable?: boolean|EditorResizable; + resizable?: boolean | EditorResizable; serialization?: EditorSerialization; stylesheets?: any; tools?: EditorTool[]; @@ -3930,7 +3937,7 @@ declare namespace kendo.ui { interface FilterMenuOptions { name?: string; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; extra?: boolean; field?: string; messages?: FilterMenuMessages; @@ -4034,7 +4041,7 @@ declare namespace kendo.ui { } interface GanttAssignments { - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; dataResourceIdField?: string; dataTaskIdField?: string; dataValueField?: string; @@ -4044,7 +4051,7 @@ declare namespace kendo.ui { field?: string; title?: string; format?: string; - width?: string|number; + width?: string | number; editable?: boolean; sortable?: boolean; } @@ -4055,7 +4062,7 @@ declare namespace kendo.ui { interface GanttEditable { confirmation?: boolean; - template?: string|Function; + template?: string | Function; } interface GanttMessagesActions { @@ -4102,15 +4109,15 @@ declare namespace kendo.ui { } interface GanttPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface GanttPdf { author?: string; - avoidLinks?: boolean|string; + avoidLinks?: boolean | string; creator?: string; date?: Date; fileName?: string; @@ -4118,7 +4125,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: GanttPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -4128,31 +4135,31 @@ declare namespace kendo.ui { interface GanttResources { dataFormatField?: string; dataColorField?: string; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; dataTextField?: string; field?: string; } interface GanttToolbarItem { name?: string; - template?: string|Function; + template?: string | Function; text?: string; } interface GanttTooltip { - template?: string|Function; + template?: string | Function; visible?: boolean; } interface GanttView { type?: string; selected?: boolean; - slotSize?: number|string; - timeHeaderTemplate?: string|Function; - dayHeaderTemplate?: string|Function; - weekHeaderTemplate?: string|Function; - monthHeaderTemplate?: string|Function; - yearHeaderTemplate?: string|Function; + slotSize?: number | string; + timeHeaderTemplate?: string | Function; + dayHeaderTemplate?: string | Function; + weekHeaderTemplate?: string | Function; + monthHeaderTemplate?: string | Function; + yearHeaderTemplate?: string | Function; resizeTooltipFormat?: string; } @@ -4162,10 +4169,10 @@ declare namespace kendo.ui { autoBind?: boolean; columnResizeHandleWidth?: number; columns?: GanttColumn[]; - currentTimeMarker?: boolean|GanttCurrentTimeMarker; - dataSource?: any|any|kendo.data.GanttDataSource; - dependencies?: any|any|kendo.data.GanttDependencyDataSource; - editable?: boolean|GanttEditable; + currentTimeMarker?: boolean | GanttCurrentTimeMarker; + dataSource?: any | any | kendo.data.GanttDataSource; + dependencies?: any | any | kendo.data.GanttDependencyDataSource; + editable?: boolean | GanttEditable; navigatable?: boolean; workDayStart?: Date; workDayEnd?: Date; @@ -4173,20 +4180,20 @@ declare namespace kendo.ui { workWeekEnd?: number; hourSpan?: number; snap?: boolean; - height?: number|string; - listWidth?: string|number; + height?: number | string; + listWidth?: string | number; messages?: GanttMessages; pdf?: GanttPdf; resizable?: boolean; selectable?: boolean; showWorkDays?: boolean; showWorkHours?: boolean; - taskTemplate?: string|Function; + taskTemplate?: string | Function; toolbar?: GanttToolbarItem[]; tooltip?: GanttTooltip; views?: GanttView[]; resources?: GanttResources; - rowHeight?: number|string; + rowHeight?: number | string; dataBinding?(e: GanttDataBindingEvent): void; dataBound?(e: GanttDataBoundEvent): void; add?(e: GanttAddEvent): void; @@ -4380,7 +4387,7 @@ declare namespace kendo.ui { } interface GridAllowCopy { - delimeter?: string|any; + delimeter?: string | any; } interface GridColumnMenuMessages { @@ -4416,7 +4423,7 @@ declare namespace kendo.ui { } interface GridColumnFilterableCell { - dataSource?: any|kendo.data.DataSource; + dataSource?: any | kendo.data.DataSource; dataTextField?: string; delay?: number; inputWidth?: number; @@ -4431,13 +4438,13 @@ declare namespace kendo.ui { interface GridColumnFilterable { cell?: GridColumnFilterableCell; multi?: boolean; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; checkAll?: boolean; itemTemplate?: Function; operators?: any; search?: boolean; ignoreCase?: boolean; - ui?: string|Function; + ui?: string | Function; } interface GridColumnSortable { @@ -4451,35 +4458,36 @@ declare namespace kendo.ui { command?: GridColumnCommandItem[]; encoded?: boolean; field?: string; - filterable?: boolean|GridColumnFilterable; + filterable?: boolean | GridColumnFilterable; footerAttributes?: any; - footerTemplate?: string|Function; + footerTemplate?: string | Function; format?: string; groupable?: boolean; - groupHeaderTemplate?: string|Function; - groupFooterTemplate?: string|Function; + groupHeaderTemplate?: string | Function; + groupFooterTemplate?: string | Function; headerAttributes?: any; - headerTemplate?: string|Function; + headerTemplate?: string | Function; hidden?: boolean; locked?: boolean; lockable?: boolean; minScreenWidth?: number; - sortable?: boolean|GridColumnSortable; - template?: string|Function; + sortable?: boolean | GridColumnSortable; + template?: string | Function; title?: string; - width?: string|number; + width?: string | number; values?: any; menu?: boolean; + type?: any; } interface GridEditable { - confirmation?: boolean|string|Function; + confirmation?: boolean | string | Function; cancelDelete?: string; confirmDelete?: string; createAt?: string; destroy?: boolean; mode?: string; - template?: string|Function; + template?: string | Function; update?: boolean; window?: any; } @@ -4592,7 +4600,7 @@ declare namespace kendo.ui { } interface GridNoRecords { - template?: string|Function; + template?: string | Function; } interface GridPageableMessages { @@ -4615,23 +4623,23 @@ declare namespace kendo.ui { numeric?: boolean; buttonCount?: number; input?: boolean; - pageSizes?: boolean|any; + pageSizes?: boolean | any; refresh?: boolean; info?: boolean; messages?: GridPageableMessages; } interface GridPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface GridPdf { allPages?: boolean; author?: string; - avoidLinks?: boolean|string; + avoidLinks?: boolean | string; creator?: string; date?: Date; fileName?: string; @@ -4639,7 +4647,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: GridPdfMargin; - paperSize?: string|any; + paperSize?: string | any; template?: string; repeatHeaders?: boolean; scale?: number; @@ -4660,38 +4668,38 @@ declare namespace kendo.ui { interface GridToolbarItem { name?: string; - template?: string|Function; + template?: string | Function; text?: string; } interface GridOptions { name?: string; - allowCopy?: boolean|GridAllowCopy; - altRowTemplate?: string|Function; + allowCopy?: boolean | GridAllowCopy; + altRowTemplate?: string | Function; autoBind?: boolean; columnResizeHandleWidth?: number; columns?: GridColumn[]; - columnMenu?: boolean|GridColumnMenu; - dataSource?: any|any|kendo.data.DataSource; - detailTemplate?: string|Function; - editable?: boolean|GridEditable; + columnMenu?: boolean | GridColumnMenu; + dataSource?: any | any | kendo.data.DataSource; + detailTemplate?: string | Function; + editable?: boolean | GridEditable; excel?: GridExcel; - filterable?: boolean|GridFilterable; - groupable?: boolean|GridGroupable; - height?: number|string; + filterable?: boolean | GridFilterable; + groupable?: boolean | GridGroupable; + height?: number | string; messages?: GridMessages; - mobile?: boolean|string; + mobile?: boolean | string; navigatable?: boolean; - noRecords?: boolean|GridNoRecords; - pageable?: boolean|GridPageable; + noRecords?: boolean | GridNoRecords; + pageable?: boolean | GridPageable; pdf?: GridPdf; reorderable?: boolean; resizable?: boolean; - rowTemplate?: string|Function; - scrollable?: boolean|GridScrollable; - selectable?: boolean|string; - sortable?: boolean|GridSortable; - toolbar?: string | ((...args:any[]) => string) | GridToolbarItem[]; + rowTemplate?: string | Function; + scrollable?: boolean | GridScrollable; + selectable?: boolean | string; + sortable?: boolean | GridSortable; + toolbar?: string | ((...args: any[]) => string) | GridToolbarItem[]; cancel?(e: GridCancelEvent): void; change?(e: GridChangeEvent): void; columnHide?(e: GridColumnHideEvent): void; @@ -4865,10 +4873,10 @@ declare namespace kendo.ui { interface ListViewOptions { name?: string; autoBind?: boolean; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; editTemplate?: Function; navigatable?: boolean; - selectable?: boolean|string; + selectable?: boolean | string; template?: Function; altTemplate?: Function; cancel?(e: ListViewCancelEvent): void; @@ -5007,9 +5015,9 @@ declare namespace kendo.ui { interface MenuOptions { name?: string; - animation?: boolean|MenuAnimation; + animation?: boolean | MenuAnimation; closeOnClick?: boolean; - dataSource?: any|any; + dataSource?: any | any; direction?: string; hoverDelay?: number; openOnClick?: boolean; @@ -5114,17 +5122,17 @@ declare namespace kendo.ui { interface MultiSelectOptions { name?: string; - animation?: boolean|MultiSelectAnimation; + animation?: boolean | MultiSelectAnimation; autoBind?: boolean; autoClose?: boolean; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; dataTextField?: string; dataValueField?: string; delay?: number; enable?: boolean; filter?: string; - fixedGroupTemplate?: string|Function; - groupTemplate?: string|Function; + fixedGroupTemplate?: string | Function; + groupTemplate?: string | Function; height?: number; highlightFirst?: boolean; ignoreCase?: boolean; @@ -5132,13 +5140,13 @@ declare namespace kendo.ui { maxSelectedItems?: number; placeholder?: string; popup?: MultiSelectPopup; - headerTemplate?: string|Function; - itemTemplate?: string|Function; + headerTemplate?: string | Function; + itemTemplate?: string | Function; tagTemplate?: string; tagMode?: string; value?: any; valuePrimitive?: boolean; - virtual?: boolean|MultiSelectVirtual; + virtual?: boolean | MultiSelectVirtual; change?(e: MultiSelectChangeEvent): void; close?(e: MultiSelectCloseEvent): void; dataBound?(e: MultiSelectDataBoundEvent): void; @@ -5227,16 +5235,16 @@ declare namespace kendo.ui { interface NotificationOptions { name?: string; allowHideAfter?: number; - animation?: any|boolean; - appendTo?: string|JQuery; + animation?: any | boolean; + appendTo?: string | JQuery; autoHideAfter?: number; button?: boolean; - height?: number|string; + height?: number | string; hideOnClick?: boolean; position?: NotificationPosition; stacking?: string; templates?: NotificationTemplate[]; - width?: number|string; + width?: number | string; hide?(e: NotificationHideEvent): void; show?(e: NotificationShowEvent): void; } @@ -5361,13 +5369,13 @@ declare namespace kendo.ui { name?: string; autoBind?: boolean; buttonCount?: number; - dataSource?: any|kendo.data.DataSource; + dataSource?: any | kendo.data.DataSource; selectTemplate?: string; linkTemplate?: string; info?: boolean; input?: boolean; numeric?: boolean; - pageSizes?: boolean|any; + pageSizes?: boolean | any; previousNext?: boolean; refresh?: boolean; messages?: PagerMessages; @@ -5475,9 +5483,9 @@ declare namespace kendo.ui { interface PanelBarOptions { name?: string; - animation?: boolean|PanelBarAnimation; + animation?: boolean | PanelBarAnimation; contentUrls?: any; - dataSource?: any|any; + dataSource?: any | any; expandMode?: string; activate?(e: PanelBarActivateEvent): void; collapse?(e: PanelBarCollapseEvent): void; @@ -5581,10 +5589,10 @@ declare namespace kendo.ui { interface PivotConfiguratorOptions { name?: string; - dataSource?: any|kendo.data.PivotDataSource; + dataSource?: any | kendo.data.PivotDataSource; filterable?: boolean; - sortable?: boolean|PivotConfiguratorSortable; - height?: number|string; + sortable?: boolean | PivotConfiguratorSortable; + height?: number | string; messages?: PivotConfiguratorMessages; } interface PivotConfiguratorEvent { @@ -5660,15 +5668,15 @@ declare namespace kendo.ui { } interface PivotGridPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface PivotGridPdf { author?: string; - avoidLinks?: boolean|string; + avoidLinks?: boolean | string; creator?: string; date?: Date; fileName?: string; @@ -5676,7 +5684,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: PivotGridPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -5689,20 +5697,20 @@ declare namespace kendo.ui { interface PivotGridOptions { name?: string; - dataSource?: any|kendo.data.PivotDataSource; + dataSource?: any | kendo.data.PivotDataSource; autoBind?: boolean; reorderable?: boolean; excel?: PivotGridExcel; pdf?: PivotGridPdf; filterable?: boolean; - sortable?: boolean|PivotGridSortable; + sortable?: boolean | PivotGridSortable; columnWidth?: number; - height?: number|string; - columnHeaderTemplate?: string|Function; - dataCellTemplate?: string|Function; - kpiStatusTemplate?: string|Function; - kpiTrendTemplate?: string|Function; - rowHeaderTemplate?: string|Function; + height?: number | string; + columnHeaderTemplate?: string | Function; + dataCellTemplate?: string | Function; + kpiStatusTemplate?: string | Function; + kpiTrendTemplate?: string | Function; + rowHeaderTemplate?: string | Function; messages?: PivotGridMessages; dataBinding?(e: PivotGridDataBindingEvent): void; dataBound?(e: PivotGridDataBoundEvent): void; @@ -5784,9 +5792,9 @@ declare namespace kendo.ui { interface PopupOptions { name?: string; adjustSize?: any; - animation?: boolean|PopupAnimation; - anchor?: string|JQuery; - appendTo?: string|JQuery; + animation?: boolean | PopupAnimation; + anchor?: string | JQuery; + appendTo?: string | JQuery; collision?: string; origin?: string; position?: string; @@ -5889,6 +5897,7 @@ declare namespace kendo.ui { destroy(): void; enable(enable: boolean): void; value(): any; + values(): any; value(selectionStart: number, selectionEnd: number): void; resize(): void; @@ -6017,19 +6026,19 @@ declare namespace kendo.ui { } interface SchedulerEditable { - confirmation?: boolean|string; + confirmation?: boolean | string; create?: boolean; destroy?: boolean; editRecurringMode?: string; move?: boolean; resize?: boolean; - template?: string|Function; + template?: string | Function; update?: boolean; window?: any; } interface SchedulerFooter { - command?: string|boolean; + command?: string | boolean; } interface SchedulerGroup { @@ -6166,15 +6175,15 @@ declare namespace kendo.ui { } interface SchedulerPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface SchedulerPdf { author?: string; - avoidLinks?: boolean|string; + avoidLinks?: boolean | string; creator?: string; date?: Date; fileName?: string; @@ -6182,7 +6191,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: SchedulerPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -6191,7 +6200,7 @@ declare namespace kendo.ui { interface SchedulerResource { dataColorField?: string; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; dataTextField?: string; dataValueField?: string; field?: string; @@ -6216,26 +6225,26 @@ declare namespace kendo.ui { } interface SchedulerView { - allDayEventTemplate?: string|Function; + allDayEventTemplate?: string | Function; allDaySlot?: boolean; - allDaySlotTemplate?: string|Function; + allDaySlotTemplate?: string | Function; columnWidth?: number; - dateHeaderTemplate?: string|Function; - dayTemplate?: string|Function; - editable?: boolean|SchedulerViewEditable; + dateHeaderTemplate?: string | Function; + dayTemplate?: string | Function; + editable?: boolean | SchedulerViewEditable; endTime?: Date; eventHeight?: number; - eventTemplate?: string|Function; - eventTimeTemplate?: string|Function; + eventTemplate?: string | Function; + eventTimeTemplate?: string | Function; group?: SchedulerViewGroup; majorTick?: number; - majorTimeHeaderTemplate?: string|Function; + majorTimeHeaderTemplate?: string | Function; minorTickCount?: number; - minorTimeHeaderTemplate?: string|Function; + minorTimeHeaderTemplate?: string | Function; selected?: boolean; selectedDateFormat?: string; showWorkHours?: boolean; - slotTemplate?: string|Function; + slotTemplate?: string | Function; startTime?: Date; title?: string; type?: string; @@ -6253,27 +6262,27 @@ declare namespace kendo.ui { interface SchedulerOptions { name?: string; - allDayEventTemplate?: string|Function; + allDayEventTemplate?: string | Function; allDaySlot?: boolean; autoBind?: boolean; - currentTimeMarker?: boolean|SchedulerCurrentTimeMarker; - dataSource?: any|any|kendo.data.SchedulerDataSource; + currentTimeMarker?: boolean | SchedulerCurrentTimeMarker; + dataSource?: any | any | kendo.data.SchedulerDataSource; date?: Date; - dateHeaderTemplate?: string|Function; - editable?: boolean|SchedulerEditable; + dateHeaderTemplate?: string | Function; + editable?: boolean | SchedulerEditable; endTime?: Date; - eventTemplate?: string|Function; - footer?: boolean|SchedulerFooter; + eventTemplate?: string | Function; + footer?: boolean | SchedulerFooter; group?: SchedulerGroup; - height?: number|string; + height?: number | string; majorTick?: number; - majorTimeHeaderTemplate?: string|Function; + majorTimeHeaderTemplate?: string | Function; max?: Date; messages?: SchedulerMessages; min?: Date; minorTickCount?: number; - minorTimeHeaderTemplate?: string|Function; - mobile?: boolean|string; + minorTimeHeaderTemplate?: string | Function; + mobile?: boolean | string; pdf?: SchedulerPdf; resources?: SchedulerResource[]; selectable?: boolean; @@ -6283,8 +6292,8 @@ declare namespace kendo.ui { timezone?: string; toolbar?: SchedulerToolbarItem[]; views?: SchedulerView[]; - groupHeaderTemplate?: string|Function; - width?: number|string; + groupHeaderTemplate?: string | Function; + width?: number | string; workDayStart?: Date; workDayEnd?: Date; workWeekStart?: number; @@ -6480,17 +6489,17 @@ declare namespace kendo.ui { name?: string; axis?: string; autoScroll?: boolean; - container?: string|JQuery; + container?: string | JQuery; connectWith?: string; cursor?: string; cursorOffset?: SortableCursorOffset; disabled?: string; filter?: string; handler?: string; - hint?: Function|string|JQuery; + hint?: Function | string | JQuery; holdToDrag?: boolean; ignore?: string; - placeholder?: Function|string|JQuery; + placeholder?: Function | string | JQuery; start?(e: SortableStartEvent): void; move?(e: SortableMoveEvent): void; end?(e: SortableEndEvent): void; @@ -6677,10 +6686,10 @@ declare namespace kendo.ui { } interface SpreadsheetPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface SpreadsheetPdf { @@ -6696,7 +6705,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: SpreadsheetPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -6720,7 +6729,7 @@ declare namespace kendo.ui { index?: number; logic?: string; type?: string; - value?: number|string|Date; + value?: number | string | Date; values?: any; } @@ -6778,7 +6787,7 @@ declare namespace kendo.ui { link?: string; textAlign?: string; underline?: boolean; - value?: number|string|boolean|Date; + value?: number | string | boolean | Date; validation?: SpreadsheetSheetRowCellValidation; verticalAlign?: string; wrap?: boolean; @@ -6816,9 +6825,9 @@ declare namespace kendo.ui { } interface SpreadsheetToolbar { - home?: boolean|any; - insert?: boolean|any; - data?: boolean|any; + home?: boolean | any; + insert?: boolean | any; + data?: boolean | any; } interface SpreadsheetInsertSheetOptions { @@ -6845,7 +6854,7 @@ declare namespace kendo.ui { rows?: number; sheets?: SpreadsheetSheet[]; sheetsbar?: boolean; - toolbar?: boolean|SpreadsheetToolbar; + toolbar?: boolean | SpreadsheetToolbar; change?(e: SpreadsheetChangeEvent): void; render?(e: SpreadsheetRenderEvent): void; excelExport?(e: SpreadsheetExcelExportEvent): void; @@ -6871,7 +6880,7 @@ declare namespace kendo.ui { } interface SpreadsheetExcelImportEvent extends SpreadsheetEvent { - file?: Blob|File; + file?: Blob | File; progress?: JQueryPromise; } @@ -6971,18 +6980,18 @@ declare namespace kendo.ui { interface TabStripOptions { name?: string; - animation?: boolean|TabStripAnimation; + animation?: boolean | TabStripAnimation; collapsible?: boolean; contentUrls?: any; dataContentField?: string; dataContentUrlField?: string; dataImageUrlField?: string; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; dataSpriteCssClass?: string; dataTextField?: string; dataUrlField?: string; navigatable?: boolean; - scrollable?: boolean|TabStripScrollable; + scrollable?: boolean | TabStripScrollable; tabPosition?: string; value?: string; activate?(e: TabStripActivateEvent): void; @@ -7073,7 +7082,7 @@ declare namespace kendo.ui { interface TimePickerOptions { name?: string; - animation?: boolean|TimePickerAnimation; + animation?: boolean | TimePickerAnimation; culture?: string; dates?: any; format?: string; @@ -7179,13 +7188,13 @@ declare namespace kendo.ui { imageUrl?: string; menuButtons?: ToolBarItemMenuButton[]; overflow?: string; - overflowTemplate?: string|Function; + overflowTemplate?: string | Function; primary?: boolean; selected?: boolean; showIcon?: string; showText?: string; spriteCssClass?: string; - template?: string|Function; + template?: string | Function; text?: string; togglable?: boolean; toggle?: Function; @@ -7280,7 +7289,7 @@ declare namespace kendo.ui { interface TooltipOptions { name?: string; autoHide?: boolean; - animation?: boolean|TooltipAnimation; + animation?: boolean | TooltipAnimation; content?: TooltipContent; callout?: boolean; filter?: string; @@ -7505,7 +7514,7 @@ declare namespace kendo.ui { } interface TreeListColumnFilterable { - ui?: string|Function; + ui?: string | Function; } interface TreeListColumnSortable { @@ -7518,16 +7527,16 @@ declare namespace kendo.ui { encoded?: boolean; expandable?: boolean; field?: string; - filterable?: boolean|TreeListColumnFilterable; - footerTemplate?: string|Function; + filterable?: boolean | TreeListColumnFilterable; + footerTemplate?: string | Function; format?: string; headerAttributes?: any; - headerTemplate?: string|Function; + headerTemplate?: string | Function; minScreenWidth?: number; - sortable?: boolean|TreeListColumnSortable; - template?: string|Function; + sortable?: boolean | TreeListColumnSortable; + template?: string | Function; title?: string; - width?: string|number; + width?: string | number; hidden?: boolean; menu?: boolean; locked?: boolean; @@ -7537,7 +7546,7 @@ declare namespace kendo.ui { interface TreeListEditable { mode?: string; move?: boolean; - template?: string|Function; + template?: string | Function; window?: any; } @@ -7586,15 +7595,15 @@ declare namespace kendo.ui { } interface TreeListPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface TreeListPdf { author?: string; - avoidLinks?: boolean|string; + avoidLinks?: boolean | string; creator?: string; date?: Date; fileName?: string; @@ -7602,7 +7611,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: TreeListPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -7625,17 +7634,17 @@ declare namespace kendo.ui { columns?: TreeListColumn[]; resizable?: boolean; reorderable?: boolean; - columnMenu?: boolean|TreeListColumnMenu; - dataSource?: any|any|kendo.data.TreeListDataSource; - editable?: boolean|TreeListEditable; + columnMenu?: boolean | TreeListColumnMenu; + dataSource?: any | any | kendo.data.TreeListDataSource; + editable?: boolean | TreeListEditable; excel?: TreeListExcel; - filterable?: boolean|TreeListFilterable; - height?: number|string; + filterable?: boolean | TreeListFilterable; + height?: number | string; messages?: TreeListMessages; pdf?: TreeListPdf; - scrollable?: boolean|any; - selectable?: boolean|string; - sortable?: boolean|TreeListSortable; + scrollable?: boolean | any; + selectable?: boolean | string; + sortable?: boolean | TreeListSortable; toolbar?: TreeListToolbarItem[]; cancel?(e: TreeListCancelEvent): void; change?(e: TreeListChangeEvent): void; @@ -7850,14 +7859,14 @@ declare namespace kendo.ui { } interface TreeViewAnimation { - collapse?: boolean|TreeViewAnimationCollapse; - expand?: boolean|TreeViewAnimationExpand; + collapse?: boolean | TreeViewAnimationCollapse; + expand?: boolean | TreeViewAnimationExpand; } interface TreeViewCheckboxes { checkChildren?: boolean; name?: string; - template?: string|Function; + template?: string | Function; } interface TreeViewMessages { @@ -7868,19 +7877,19 @@ declare namespace kendo.ui { interface TreeViewOptions { name?: string; - animation?: boolean|TreeViewAnimation; + animation?: boolean | TreeViewAnimation; autoBind?: boolean; autoScroll?: boolean; - checkboxes?: boolean|TreeViewCheckboxes; + checkboxes?: boolean | TreeViewCheckboxes; dataImageUrlField?: string; - dataSource?: any|any|kendo.data.HierarchicalDataSource; + dataSource?: any | any | kendo.data.HierarchicalDataSource; dataSpriteCssClassField?: string; - dataTextField?: string|any; + dataTextField?: string | any; dataUrlField?: string; dragAndDrop?: boolean; loadOnDemand?: boolean; messages?: TreeViewMessages; - template?: string|Function; + template?: string | Function; change?(e: TreeViewEvent): void; check?(e: TreeViewCheckEvent): void; collapse?(e: TreeViewCollapseEvent): void; @@ -8013,7 +8022,7 @@ declare namespace kendo.ui { localization?: UploadLocalization; multiple?: boolean; showFileList?: boolean; - template?: string|Function; + template?: string | Function; cancel?(e: UploadCancelEvent): void; complete?(e: UploadEvent): void; error?(e: UploadErrorEvent): void; @@ -8167,8 +8176,8 @@ declare namespace kendo.ui { } interface WindowPosition { - top?: number|string; - left?: number|string; + top?: number | string; + left?: number | string; } interface WindowRefreshOptions { @@ -8183,13 +8192,13 @@ declare namespace kendo.ui { interface WindowOptions { name?: string; actions?: any; - animation?: boolean|WindowAnimation; - appendTo?: any|string; + animation?: boolean | WindowAnimation; + appendTo?: any | string; autoFocus?: boolean; content?: WindowContent; draggable?: boolean; iframe?: boolean; - height?: number|string; + height?: number | string; maxHeight?: number; maxWidth?: number; minHeight?: number; @@ -8199,9 +8208,9 @@ declare namespace kendo.ui { position?: WindowPosition; resizable?: boolean; scrollable?: boolean; - title?: string|boolean; + title?: string | boolean; visible?: boolean; - width?: number|string; + width?: number | string; activate?(e: WindowEvent): void; close?(e: WindowCloseEvent): void; deactivate?(e: WindowEvent): void; @@ -8371,7 +8380,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartAxisDefaultsCrosshairTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -8399,7 +8408,7 @@ declare namespace kendo.dataviz.ui { interface ChartAxisDefaultsLabelsRotation { align?: string; - angle?: number|string; + angle?: number | string; } interface ChartAxisDefaultsLabels { @@ -8411,7 +8420,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartAxisDefaultsLabelsRotation; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; visual?: Function; } @@ -8549,7 +8558,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartCategoryAxisItemCrosshairTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -8591,7 +8600,7 @@ declare namespace kendo.dataviz.ui { interface ChartCategoryAxisItemLabelsRotation { align?: string; - angle?: number|string; + angle?: number | string; } interface ChartCategoryAxisItemLabels { @@ -8608,7 +8617,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartCategoryAxisItemLabelsRotation; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; visual?: Function; } @@ -8680,7 +8689,7 @@ declare namespace kendo.dataviz.ui { border?: ChartCategoryAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -8726,7 +8735,7 @@ declare namespace kendo.dataviz.ui { border?: ChartCategoryAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -8804,7 +8813,7 @@ declare namespace kendo.dataviz.ui { interface ChartCategoryAxisItem { autoBaseUnitSteps?: ChartCategoryAxisItemAutoBaseUnitSteps; - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; background?: string; baseUnit?: string; baseUnitStep?: any; @@ -8833,6 +8842,7 @@ declare namespace kendo.dataviz.ui { type?: string; visible?: boolean; weekStartDay?: number; + axisCrossingValues?: number[]; notes?: ChartCategoryAxisItemNotes; } @@ -8867,7 +8877,7 @@ declare namespace kendo.dataviz.ui { interface ChartLegendInactiveItemsLabels { color?: string; font?: string; - template?: string|Function; + template?: string | Function; } interface ChartLegendInactiveItems { @@ -8898,7 +8908,7 @@ declare namespace kendo.dataviz.ui { font?: string; margin?: ChartLegendLabelsMargin; padding?: ChartLegendLabelsPadding; - template?: string|Function; + template?: string | Function; } interface ChartLegendMargin { @@ -8996,10 +9006,10 @@ declare namespace kendo.dataviz.ui { } interface ChartPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface ChartPdf { @@ -9011,7 +9021,7 @@ declare namespace kendo.dataviz.ui { keywords?: string; landscape?: boolean; margin?: ChartPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -9047,10 +9057,10 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemBorder { - color?: string|Function; - dashType?: string|Function; - opacity?: number|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + opacity?: number | Function; + width?: number | Function; } interface ChartSeriesItemConnectors { @@ -9065,26 +9075,26 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemErrorBars { - value?: string|number|any|Function; + value?: string | number | any | Function; visual?: Function; - xValue?: string|number|any|Function; - yValue?: string|number|any|Function; + xValue?: string | number | any | Function; + yValue?: string | number | any | Function; endCaps?: boolean; color?: string; line?: ChartSeriesItemErrorBarsLine; } interface ChartSeriesItemExtremesBorder { - color?: string|Function; - width?: number|Function; + color?: string | Function; + width?: number | Function; } interface ChartSeriesItemExtremes { - background?: string|Function; + background?: string | Function; border?: ChartSeriesItemExtremesBorder; - size?: number|Function; - type?: string|Function; - rotation?: number|Function; + size?: number | Function; + type?: string | Function; + rotation?: number | Function; } interface ChartSeriesItemHighlightBorder { @@ -9110,15 +9120,15 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemLabelsBorder { - color?: string|Function; - dashType?: string|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + width?: number | Function; } interface ChartSeriesItemLabelsFromBorder { - color?: string|Function; - dashType?: string|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + width?: number | Function; } interface ChartSeriesItemLabelsFromMargin { @@ -9136,16 +9146,16 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemLabelsFrom { - background?: string|Function; + background?: string | Function; border?: ChartSeriesItemLabelsFromBorder; - color?: string|Function; - font?: string|Function; - format?: string|Function; + color?: string | Function; + font?: string | Function; + format?: string | Function; margin?: ChartSeriesItemLabelsFromMargin; padding?: ChartSeriesItemLabelsFromPadding; - position?: string|Function; - template?: string|Function; - visible?: boolean|Function; + position?: string | Function; + template?: string | Function; + visible?: boolean | Function; } interface ChartSeriesItemLabelsMargin { @@ -9163,9 +9173,9 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemLabelsToBorder { - color?: string|Function; - dashType?: string|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + width?: number | Function; } interface ChartSeriesItemLabelsToMargin { @@ -9183,31 +9193,31 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemLabelsTo { - background?: string|Function; + background?: string | Function; border?: ChartSeriesItemLabelsToBorder; - color?: string|Function; - font?: string|Function; - format?: string|Function; + color?: string | Function; + font?: string | Function; + format?: string | Function; margin?: ChartSeriesItemLabelsToMargin; padding?: ChartSeriesItemLabelsToPadding; - position?: string|Function; - template?: string|Function; - visible?: boolean|Function; + position?: string | Function; + template?: string | Function; + visible?: boolean | Function; } interface ChartSeriesItemLabels { align?: string; - background?: string|Function; + background?: string | Function; border?: ChartSeriesItemLabelsBorder; - color?: string|Function; + color?: string | Function; distance?: number; - font?: string|Function; - format?: string|Function; + font?: string | Function; + format?: string | Function; margin?: ChartSeriesItemLabelsMargin; padding?: ChartSeriesItemLabelsPadding; - position?: string|Function; - template?: string|Function; - visible?: boolean|Function; + position?: string | Function; + template?: string | Function; + visible?: boolean | Function; visual?: Function; from?: ChartSeriesItemLabelsFrom; to?: ChartSeriesItemLabelsTo; @@ -9228,18 +9238,18 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemMarkersBorder { - color?: string|Function; - width?: number|Function; + color?: string | Function; + width?: number | Function; } interface ChartSeriesItemMarkers { - background?: string|Function; + background?: string | Function; border?: ChartSeriesItemMarkersBorder; - size?: number|Function; - type?: string|Function; - visible?: boolean|Function; + size?: number | Function; + type?: string | Function; + visible?: boolean | Function; visual?: Function; - rotation?: number|Function; + rotation?: number | Function; } interface ChartSeriesItemNegativeValues { @@ -9271,7 +9281,7 @@ declare namespace kendo.dataviz.ui { border?: ChartSeriesItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -9293,16 +9303,16 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemOutliersBorder { - color?: string|Function; - width?: number|Function; + color?: string | Function; + width?: number | Function; } interface ChartSeriesItemOutliers { - background?: string|Function; + background?: string | Function; border?: ChartSeriesItemOutliersBorder; - size?: number|Function; - type?: string|Function; - rotation?: number|Function; + size?: number | Function; + type?: string | Function; + rotation?: number | Function; } interface ChartSeriesItemOverlay { @@ -9315,18 +9325,18 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemTargetBorder { - color?: string|Function; - dashType?: string|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + width?: number | Function; } interface ChartSeriesItemTargetLine { - width?: any|Function; + width?: any | Function; } interface ChartSeriesItemTarget { border?: ChartSeriesItemTargetBorder; - color?: string|Function; + color?: string | Function; line?: ChartSeriesItemTargetLine; } @@ -9349,23 +9359,23 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartSeriesItemTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } interface ChartSeriesItem { - aggregate?: string|Function; + aggregate?: string | Function; axis?: string; border?: ChartSeriesItemBorder; categoryField?: string; closeField?: string; - color?: string|Function; + color?: string | Function; colorField?: string; connectors?: ChartSeriesItemConnectors; currentField?: string; dashType?: string; data?: any; - downColor?: string|Function; + downColor?: string | Function; downColorField?: string; segmentSpacing?: number; summaryField?: string; @@ -9416,7 +9426,7 @@ declare namespace kendo.dataviz.ui { size?: number; sizeField?: string; spacing?: number; - stack?: boolean|ChartSeriesItemStack; + stack?: boolean | ChartSeriesItemStack; startAngle?: number; target?: ChartSeriesItemTarget; targetField?: string; @@ -9475,7 +9485,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: ChartSeriesDefaultsLabelsFromMargin; padding?: ChartSeriesDefaultsLabelsFromPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -9521,7 +9531,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: ChartSeriesDefaultsLabelsToMargin; padding?: ChartSeriesDefaultsLabelsToPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -9533,7 +9543,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: ChartSeriesDefaultsLabelsMargin; padding?: ChartSeriesDefaultsLabelsPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; visual?: Function; from?: ChartSeriesDefaultsLabelsFrom; @@ -9564,7 +9574,7 @@ declare namespace kendo.dataviz.ui { border?: ChartSeriesDefaultsNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -9611,7 +9621,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartSeriesDefaultsTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -9632,7 +9642,7 @@ declare namespace kendo.dataviz.ui { scatter?: any; scatterLine?: any; spacing?: number; - stack?: boolean|ChartSeriesDefaultsStack; + stack?: boolean | ChartSeriesDefaultsStack; type?: string; tooltip?: ChartSeriesDefaultsTooltip; verticalArea?: any; @@ -9695,8 +9705,8 @@ declare namespace kendo.dataviz.ui { opacity?: number; padding?: ChartTooltipPadding; shared?: boolean; - sharedTemplate?: string|Function; - template?: string|Function; + sharedTemplate?: string | Function; + template?: string | Function; visible?: boolean; } @@ -9720,7 +9730,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartValueAxisItemCrosshairTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -9754,7 +9764,7 @@ declare namespace kendo.dataviz.ui { interface ChartValueAxisItemLabelsRotation { align?: string; - angle?: number|string; + angle?: number | string; } interface ChartValueAxisItemLabels { @@ -9769,7 +9779,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartValueAxisItemLabelsRotation; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; visual?: Function; } @@ -9842,7 +9852,7 @@ declare namespace kendo.dataviz.ui { border?: ChartValueAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -9888,7 +9898,7 @@ declare namespace kendo.dataviz.ui { border?: ChartValueAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -9952,7 +9962,7 @@ declare namespace kendo.dataviz.ui { } interface ChartValueAxisItem { - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; background?: string; color?: string; crosshair?: ChartValueAxisItemCrosshair; @@ -9997,7 +10007,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartXAxisItemCrosshairTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -10039,7 +10049,7 @@ declare namespace kendo.dataviz.ui { interface ChartXAxisItemLabelsRotation { align?: string; - angle?: number|string; + angle?: number | string; } interface ChartXAxisItemLabels { @@ -10056,7 +10066,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartXAxisItemLabelsRotation; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; visual?: Function; } @@ -10128,7 +10138,7 @@ declare namespace kendo.dataviz.ui { border?: ChartXAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -10174,7 +10184,7 @@ declare namespace kendo.dataviz.ui { border?: ChartXAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -10238,7 +10248,7 @@ declare namespace kendo.dataviz.ui { } interface ChartXAxisItem { - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; background?: string; baseUnit?: string; color?: string; @@ -10285,7 +10295,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartYAxisItemCrosshairTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -10344,7 +10354,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartYAxisItemLabelsRotation; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; visual?: Function; } @@ -10416,7 +10426,7 @@ declare namespace kendo.dataviz.ui { border?: ChartYAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -10462,7 +10472,7 @@ declare namespace kendo.dataviz.ui { border?: ChartYAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -10526,7 +10536,7 @@ declare namespace kendo.dataviz.ui { } interface ChartYAxisItem { - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; background?: string; baseUnit?: string; color?: string; @@ -10562,8 +10572,8 @@ declare namespace kendo.dataviz.ui { } interface ChartZoomable { - mousewheel?: boolean|ChartZoomableMousewheel; - selection?: boolean|ChartZoomableSelection; + mousewheel?: boolean | ChartZoomableMousewheel; + selection?: boolean | ChartZoomableSelection; } interface ChartExportImageOptions { @@ -10596,13 +10606,13 @@ declare namespace kendo.dataviz.ui { interface ChartOptions { name?: string; autoBind?: boolean; - axisDefaults?: ChartAxisDefaults; + axisDefaults?: any; categoryAxis?: ChartCategoryAxisItem[]; + valueAxis?: ChartValueAxisItem[]; chartArea?: ChartChartArea; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any; legend?: ChartLegend; panes?: ChartPane[]; - pannable?: boolean|ChartPannable; pdf?: ChartPdf; plotArea?: ChartPlotArea; renderAs?: string; @@ -10613,10 +10623,8 @@ declare namespace kendo.dataviz.ui { title?: ChartTitle; tooltip?: ChartTooltip; transitions?: boolean; - valueAxis?: ChartValueAxisItem[]; xAxis?: ChartXAxisItem[]; yAxis?: ChartYAxisItem[]; - zoomable?: boolean|ChartZoomable; axisLabelClick?(e: ChartAxisLabelClickEvent): void; legendItemClick?(e: ChartLegendItemClickEvent): void; legendItemHover?(e: ChartLegendItemHoverEvent): void; @@ -10627,13 +10635,14 @@ declare namespace kendo.dataviz.ui { noteClick?(e: ChartNoteClickEvent): void; noteHover?(e: ChartNoteHoverEvent): void; plotAreaClick?(e: ChartPlotAreaClickEvent): void; - plotAreaHover?(e: ChartPlotAreaHoverEvent): void; + pannable?:any; render?(e: ChartEvent): void; select?(e: ChartSelectEvent): void; selectEnd?(e: ChartSelectEndEvent): void; selectStart?(e: ChartSelectStartEvent): void; seriesClick?(e: ChartSeriesClickEvent): void; seriesHover?(e: ChartSeriesHoverEvent): void; + zoomable?:any; zoom?(e: ChartZoomEvent): void; zoomEnd?(e: ChartZoomEndEvent): void; zoomStart?(e: ChartZoomStartEvent): void; @@ -10866,7 +10875,7 @@ declare namespace kendo.dataviz.ui { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string|Function; + template?: string | Function; text?: string; visual?: Function; } @@ -10947,7 +10956,7 @@ declare namespace kendo.dataviz.ui { interface DiagramConnectionDefaults { content?: DiagramConnectionDefaultsContent; - editable?: boolean|DiagramConnectionDefaultsEditable; + editable?: boolean | DiagramConnectionDefaultsEditable; endCap?: DiagramConnectionDefaultsEndCap; fromConnector?: string; hover?: DiagramConnectionDefaultsHover; @@ -10965,7 +10974,7 @@ declare namespace kendo.dataviz.ui { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string|Function; + template?: string | Function; text?: string; visual?: Function; } @@ -11059,7 +11068,7 @@ declare namespace kendo.dataviz.ui { interface DiagramConnection { content?: DiagramConnectionContent; - editable?: boolean|DiagramConnectionEditable; + editable?: boolean | DiagramConnectionEditable; endCap?: DiagramConnectionEndCap; from?: DiagramConnectionFrom; fromConnector?: string; @@ -11078,7 +11087,7 @@ declare namespace kendo.dataviz.ui { } interface DiagramEditableDrag { - snap?: boolean|DiagramEditableDragSnap; + snap?: boolean | DiagramEditableDragSnap; } interface DiagramEditableResizeHandlesFill { @@ -11141,12 +11150,12 @@ declare namespace kendo.dataviz.ui { } interface DiagramEditable { - connectionTemplate?: string|Function; - drag?: boolean|DiagramEditableDrag; + connectionTemplate?: string | Function; + drag?: boolean | DiagramEditableDrag; remove?: boolean; - resize?: boolean|DiagramEditableResize; - rotate?: boolean|DiagramEditableRotate; - shapeTemplate?: string|Function; + resize?: boolean | DiagramEditableResize; + rotate?: boolean | DiagramEditableRotate; + shapeTemplate?: string | Function; tools?: DiagramEditableTool[]; } @@ -11182,10 +11191,10 @@ declare namespace kendo.dataviz.ui { } interface DiagramPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface DiagramPdf { @@ -11197,7 +11206,7 @@ declare namespace kendo.dataviz.ui { keywords?: string; landscape?: boolean; margin?: DiagramPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -11294,7 +11303,7 @@ declare namespace kendo.dataviz.ui { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string|Function; + template?: string | Function; text?: string; } @@ -11354,7 +11363,7 @@ declare namespace kendo.dataviz.ui { connectors?: DiagramShapeDefaultsConnector[]; connectorDefaults?: DiagramShapeDefaultsConnectorDefaults; content?: DiagramShapeDefaultsContent; - editable?: boolean|DiagramShapeDefaultsEditable; + editable?: boolean | DiagramShapeDefaultsEditable; fill?: DiagramShapeDefaultsFill; height?: number; hover?: DiagramShapeDefaultsHover; @@ -11452,7 +11461,7 @@ declare namespace kendo.dataviz.ui { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string|Function; + template?: string | Function; text?: string; } @@ -11510,7 +11519,7 @@ declare namespace kendo.dataviz.ui { connectors?: DiagramShapeConnector[]; connectorDefaults?: DiagramShapeConnectorDefaults; content?: DiagramShapeContent; - editable?: boolean|DiagramShapeEditable; + editable?: boolean | DiagramShapeEditable; fill?: DiagramShapeFill; height?: number; hover?: DiagramShapeHover; @@ -11547,16 +11556,16 @@ declare namespace kendo.dataviz.ui { autoBind?: boolean; connectionDefaults?: DiagramConnectionDefaults; connections?: DiagramConnection[]; - connectionsDataSource?: any|any|kendo.data.DataSource; - dataSource?: any|any|kendo.data.DataSource; - editable?: boolean|DiagramEditable; + connectionsDataSource?: any | any | kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; + editable?: boolean | DiagramEditable; layout?: DiagramLayout; - pannable?: boolean|DiagramPannable; + pannable?: boolean | DiagramPannable; pdf?: DiagramPdf; - selectable?: boolean|DiagramSelectable; + selectable?: boolean | DiagramSelectable; shapeDefaults?: DiagramShapeDefaults; shapes?: DiagramShape[]; - template?: string|Function; + template?: string | Function; zoom?: number; zoomMax?: number; zoomMin?: number; @@ -11764,7 +11773,7 @@ declare namespace kendo.dataviz.ui { interface LinearGaugePointerItem { border?: LinearGaugePointerItemBorder; color?: string; - margin?: number|any; + margin?: number | any; opacity?: number; shape?: string; size?: number; @@ -11800,7 +11809,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: LinearGaugeScaleLabelsMargin; padding?: LinearGaugeScaleLabelsPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -11932,9 +11941,9 @@ declare namespace kendo.dataviz.ui { } interface MapControls { - attribution?: boolean|MapControlsAttribution; - navigator?: boolean|MapControlsNavigator; - zoom?: boolean|MapControlsZoom; + attribution?: boolean | MapControlsAttribution; + navigator?: boolean | MapControlsNavigator; + zoom?: boolean | MapControlsZoom; } interface MapLayerDefaultsBing { @@ -11968,7 +11977,7 @@ declare namespace kendo.dataviz.ui { maxSize?: number; minSize?: number; style?: MapLayerDefaultsBubbleStyle; - symbol?: string|Function; + symbol?: string | Function; } interface MapLayerDefaultsMarkerTooltipAnimationClose { @@ -12102,8 +12111,8 @@ declare namespace kendo.dataviz.ui { interface MapLayer { attribution?: string; autoBind?: boolean; - dataSource?: any|any|kendo.data.DataSource; - extent?: any|kendo.dataviz.map.Extent; + dataSource?: any | any | kendo.data.DataSource; + extent?: any | kendo.dataviz.map.Extent; key?: string; imagerySet?: string; culture?: string; @@ -12116,7 +12125,7 @@ declare namespace kendo.dataviz.ui { minSize?: number; opacity?: number; subdomains?: any; - symbol?: string|Function; + symbol?: string | Function; type?: string; style?: MapLayerStyle; urlTemplate?: string; @@ -12196,7 +12205,7 @@ declare namespace kendo.dataviz.ui { } interface MapMarker { - location?: any|kendo.dataviz.map.Location; + location?: any | kendo.dataviz.map.Location; shape?: string; title?: string; tooltip?: MapMarkerTooltip; @@ -12204,7 +12213,7 @@ declare namespace kendo.dataviz.ui { interface MapOptions { name?: string; - center?: any|kendo.dataviz.map.Location; + center?: any | kendo.dataviz.map.Location; controls?: MapControls; layerDefaults?: MapLayerDefaults; layers?: MapLayer[]; @@ -12369,8 +12378,8 @@ declare namespace kendo.dataviz.ui { errorCorrection?: string; padding?: number; renderAs?: string; - size?: number|string; - value?: number|string; + size?: number | string; + value?: number | string; } interface QRCodeEvent { sender: QRCode; @@ -12470,7 +12479,7 @@ declare namespace kendo.dataviz.ui { margin?: RadialGaugeScaleLabelsMargin; padding?: RadialGaugeScaleLabelsPadding; position?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -12575,8 +12584,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -12601,13 +12610,13 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number|any; + margin?: number | any; mirror?: boolean; - padding?: number|any; + padding?: number | any; rotation?: number; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; culture?: string; dateFormats?: any; @@ -12680,7 +12689,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineCategoryAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -12726,7 +12735,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineCategoryAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -12765,7 +12774,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineCategoryAxisItemTitleBorder; color?: string; font?: string; - margin?: number|any; + margin?: number | any; position?: string; rotation?: number; text?: string; @@ -12773,7 +12782,7 @@ declare namespace kendo.dataviz.ui { } interface SparklineCategoryAxisItem { - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; categories?: any; color?: string; field?: string; @@ -12813,7 +12822,7 @@ declare namespace kendo.dataviz.ui { opacity?: number; border?: SparklineChartAreaBorder; height?: number; - margin?: number|any; + margin?: number | any; width?: number; } @@ -12827,14 +12836,14 @@ declare namespace kendo.dataviz.ui { background?: string; opacity?: number; border?: SparklinePlotAreaBorder; - margin?: number|any; + margin?: number | any; } interface SparklineSeriesItemBorder { - color?: string|Function; - dashType?: string|Function; - opacity?: number|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + opacity?: number | Function; + width?: number | Function; } interface SparklineSeriesItemConnectors { @@ -12857,24 +12866,24 @@ declare namespace kendo.dataviz.ui { } interface SparklineSeriesItemLabelsBorder { - color?: string|Function; - dashType?: string|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + width?: number | Function; } interface SparklineSeriesItemLabels { align?: string; - background?: string|Function; + background?: string | Function; border?: SparklineSeriesItemLabelsBorder; - color?: string|Function; + color?: string | Function; distance?: number; - font?: string|Function; - format?: string|Function; - margin?: number|any; - padding?: number|any; - position?: string|Function; - template?: string|Function; - visible?: boolean|Function; + font?: string | Function; + format?: string | Function; + margin?: number | any; + padding?: number | any; + position?: string | Function; + template?: string | Function; + visible?: boolean | Function; } interface SparklineSeriesItemLine { @@ -12885,17 +12894,17 @@ declare namespace kendo.dataviz.ui { } interface SparklineSeriesItemMarkersBorder { - color?: string|Function; - width?: number|Function; + color?: string | Function; + width?: number | Function; } interface SparklineSeriesItemMarkers { - background?: string|Function; + background?: string | Function; border?: SparklineSeriesItemMarkersBorder; - size?: number|Function; - type?: string|Function; - visible?: boolean|Function; - rotation?: number|Function; + size?: number | Function; + type?: string | Function; + visible?: boolean | Function; + rotation?: number | Function; } interface SparklineSeriesItemNotesIconBorder { @@ -12922,7 +12931,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineSeriesItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -12952,18 +12961,18 @@ declare namespace kendo.dataviz.ui { } interface SparklineSeriesItemTargetBorder { - color?: string|Function; - dashType?: string|Function; + color?: string | Function; + dashType?: string | Function; width?: number; } interface SparklineSeriesItemTargetLine { - width?: any|Function; + width?: any | Function; } interface SparklineSeriesItemTarget { line?: SparklineSeriesItemTargetLine; - color?: string|Function; + color?: string | Function; border?: SparklineSeriesItemTargetBorder; } @@ -12978,8 +12987,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -12993,11 +13002,11 @@ declare namespace kendo.dataviz.ui { field?: string; name?: string; highlight?: SparklineSeriesItemHighlight; - aggregate?: string|Function; + aggregate?: string | Function; axis?: string; border?: SparklineSeriesItemBorder; categoryField?: string; - color?: string|Function; + color?: string | Function; colorField?: string; connectors?: SparklineSeriesItemConnectors; gap?: number; @@ -13013,7 +13022,7 @@ declare namespace kendo.dataviz.ui { size?: number; startAngle?: number; spacing?: number; - stack?: boolean|SparklineSeriesItemStack; + stack?: boolean | SparklineSeriesItemStack; tooltip?: SparklineSeriesItemTooltip; width?: number; target?: SparklineSeriesItemTarget; @@ -13039,9 +13048,9 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number|any; - padding?: number|any; - template?: string|Function; + margin?: number | any; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -13060,8 +13069,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -13076,7 +13085,7 @@ declare namespace kendo.dataviz.ui { overlay?: any; pie?: any; spacing?: number; - stack?: boolean|SparklineSeriesDefaultsStack; + stack?: boolean | SparklineSeriesDefaultsStack; type?: string; tooltip?: SparklineSeriesDefaultsTooltip; } @@ -13092,8 +13101,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; shared?: boolean; sharedTemplate?: string; @@ -13110,8 +13119,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -13136,13 +13145,13 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number|any; + margin?: number | any; mirror?: boolean; - padding?: number|any; + padding?: number | any; rotation?: number; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -13212,7 +13221,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineValueAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -13258,7 +13267,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineValueAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -13297,8 +13306,8 @@ declare namespace kendo.dataviz.ui { border?: SparklineValueAxisItemTitleBorder; color?: string; font?: string; - margin?: number|any; - padding?: number|any; + margin?: number | any; + padding?: number | any; position?: string; rotation?: number; text?: string; @@ -13306,7 +13315,7 @@ declare namespace kendo.dataviz.ui { } interface SparklineValueAxisItem { - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; color?: string; labels?: SparklineValueAxisItemLabels; line?: SparklineValueAxisItemLine; @@ -13502,8 +13511,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -13528,13 +13537,13 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number|any; + margin?: number | any; mirror?: boolean; - padding?: number|any; + padding?: number | any; rotation?: number; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; culture?: string; dateFormats?: any; @@ -13607,7 +13616,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartCategoryAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -13653,7 +13662,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartCategoryAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -13705,7 +13714,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartCategoryAxisItemTitleBorder; color?: string; font?: string; - margin?: number|any; + margin?: number | any; position?: string; rotation?: number; text?: string; @@ -13713,7 +13722,7 @@ declare namespace kendo.dataviz.ui { } interface StockChartCategoryAxisItem { - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; categories?: any; color?: string; field?: string; @@ -13756,7 +13765,7 @@ declare namespace kendo.dataviz.ui { opacity?: number; border?: StockChartChartAreaBorder; height?: number; - margin?: number|any; + margin?: number | any; width?: number; } @@ -13797,10 +13806,10 @@ declare namespace kendo.dataviz.ui { border?: StockChartLegendBorder; item?: StockChartLegendItem; labels?: StockChartLegendLabels; - margin?: number|any; + margin?: number | any; offsetX?: number; offsetY?: number; - padding?: number|any; + padding?: number | any; position?: string; reverse?: boolean; visible?: boolean; @@ -13837,7 +13846,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: StockChartNavigatorCategoryAxisItemCrosshairTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -13891,7 +13900,7 @@ declare namespace kendo.dataviz.ui { rotation?: number; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -13962,7 +13971,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartNavigatorCategoryAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -14008,7 +14017,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartNavigatorCategoryAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -14071,7 +14080,7 @@ declare namespace kendo.dataviz.ui { interface StockChartNavigatorCategoryAxisItem { autoBaseUnitSteps?: StockChartNavigatorCategoryAxisItemAutoBaseUnitSteps; - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; background?: string; baseUnit?: string; baseUnitStep?: any; @@ -14100,7 +14109,7 @@ declare namespace kendo.dataviz.ui { interface StockChartNavigatorHint { visible?: boolean; - template?: string|Function; + template?: string | Function; format?: string; } @@ -14201,10 +14210,10 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number|any; - padding?: number|any; + margin?: number | any; + padding?: number | any; position?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -14222,7 +14231,7 @@ declare namespace kendo.dataviz.ui { interface StockChartNavigatorSeriesItemMarkers { background?: string; border?: StockChartNavigatorSeriesItemMarkersBorder; - rotation?: number|Function; + rotation?: number | Function; size?: number; type?: string; visible?: boolean; @@ -14248,8 +14257,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -14262,7 +14271,7 @@ declare namespace kendo.dataviz.ui { categoryField?: string; name?: string; highlight?: StockChartNavigatorSeriesItemHighlight; - aggregate?: string|Function; + aggregate?: string | Function; axis?: string; border?: StockChartNavigatorSeriesItemBorder; closeField?: string; @@ -14281,7 +14290,7 @@ declare namespace kendo.dataviz.ui { openField?: string; overlay?: StockChartNavigatorSeriesItemOverlay; spacing?: number; - stack?: boolean|StockChartNavigatorSeriesItemStack; + stack?: boolean | StockChartNavigatorSeriesItemStack; tooltip?: StockChartNavigatorSeriesItemTooltip; width?: number; } @@ -14315,7 +14324,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartPaneTitleBorder; color?: string; font?: string; - margin?: number|any; + margin?: number | any; position?: string; text?: string; visible?: boolean; @@ -14323,8 +14332,8 @@ declare namespace kendo.dataviz.ui { interface StockChartPane { name?: string; - margin?: number|any; - padding?: number|any; + margin?: number | any; + padding?: number | any; background?: string; border?: StockChartPaneBorder; clip?: boolean; @@ -14333,10 +14342,10 @@ declare namespace kendo.dataviz.ui { } interface StockChartPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface StockChartPdf { @@ -14348,7 +14357,7 @@ declare namespace kendo.dataviz.ui { keywords?: string; landscape?: boolean; margin?: StockChartPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -14365,14 +14374,14 @@ declare namespace kendo.dataviz.ui { background?: string; opacity?: number; border?: StockChartPlotAreaBorder; - margin?: number|any; + margin?: number | any; } interface StockChartSeriesItemBorder { - color?: string|Function; - dashType?: string|Function; - opacity?: number|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + opacity?: number | Function; + width?: number | Function; } interface StockChartSeriesItemHighlightBorder { @@ -14396,22 +14405,22 @@ declare namespace kendo.dataviz.ui { } interface StockChartSeriesItemLabelsBorder { - color?: string|Function; - dashType?: string|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + width?: number | Function; } interface StockChartSeriesItemLabels { - background?: string|Function; + background?: string | Function; border?: StockChartSeriesItemLabelsBorder; - color?: string|Function; - font?: string|Function; - format?: string|Function; - margin?: number|any; - padding?: number|any; - position?: string|Function; - template?: string|Function; - visible?: boolean|Function; + color?: string | Function; + font?: string | Function; + format?: string | Function; + margin?: number | any; + padding?: number | any; + position?: string | Function; + template?: string | Function; + visible?: boolean | Function; } interface StockChartSeriesItemLine { @@ -14422,17 +14431,17 @@ declare namespace kendo.dataviz.ui { } interface StockChartSeriesItemMarkersBorder { - color?: string|Function; - width?: number|Function; + color?: string | Function; + width?: number | Function; } interface StockChartSeriesItemMarkers { - background?: string|Function; + background?: string | Function; border?: StockChartSeriesItemMarkersBorder; - size?: number|Function; - rotation?: number|Function; - type?: string|Function; - visible?: boolean|Function; + size?: number | Function; + rotation?: number | Function; + type?: string | Function; + visible?: boolean | Function; } interface StockChartSeriesItemNotesIconBorder { @@ -14459,7 +14468,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartSeriesItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -14489,18 +14498,18 @@ declare namespace kendo.dataviz.ui { } interface StockChartSeriesItemTargetBorder { - color?: string|Function; - dashType?: string|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + width?: number | Function; } interface StockChartSeriesItemTargetLine { - width?: any|Function; + width?: any | Function; } interface StockChartSeriesItemTarget { line?: StockChartSeriesItemTargetLine; - color?: string|Function; + color?: string | Function; border?: StockChartSeriesItemTargetBorder; } @@ -14515,8 +14524,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -14531,13 +14540,13 @@ declare namespace kendo.dataviz.ui { targetField?: string; name?: string; highlight?: StockChartSeriesItemHighlight; - aggregate?: string|Function; + aggregate?: string | Function; axis?: string; border?: StockChartSeriesItemBorder; closeField?: string; - color?: string|Function; + color?: string | Function; colorField?: string; - downColor?: string|Function; + downColor?: string | Function; downColorField?: string; gap?: number; labels?: StockChartSeriesItemLabels; @@ -14551,7 +14560,7 @@ declare namespace kendo.dataviz.ui { openField?: string; overlay?: StockChartSeriesItemOverlay; spacing?: number; - stack?: boolean|StockChartSeriesItemStack; + stack?: boolean | StockChartSeriesItemStack; tooltip?: StockChartSeriesItemTooltip; visibleInLegend?: boolean; width?: number; @@ -14578,9 +14587,9 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number|any; - padding?: number|any; - template?: string|Function; + margin?: number | any; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -14599,8 +14608,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -14616,7 +14625,7 @@ declare namespace kendo.dataviz.ui { overlay?: any; pie?: any; spacing?: number; - stack?: boolean|StockChartSeriesDefaultsStack; + stack?: boolean | StockChartSeriesDefaultsStack; type?: string; tooltip?: StockChartSeriesDefaultsTooltip; } @@ -14633,8 +14642,8 @@ declare namespace kendo.dataviz.ui { border?: StockChartTitleBorder; font?: string; color?: string; - margin?: number|any; - padding?: number|any; + margin?: number | any; + padding?: number | any; position?: string; text?: string; visible?: boolean; @@ -14651,8 +14660,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; shared?: boolean; sharedTemplate?: string; @@ -14669,8 +14678,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -14695,13 +14704,13 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number|any; + margin?: number | any; mirror?: boolean; - padding?: number|any; + padding?: number | any; rotation?: number; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -14771,7 +14780,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartValueAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -14817,7 +14826,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartValueAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -14856,8 +14865,8 @@ declare namespace kendo.dataviz.ui { border?: StockChartValueAxisItemTitleBorder; color?: string; font?: string; - margin?: number|any; - padding?: number|any; + margin?: number | any; + padding?: number | any; position?: string; rotation?: number; text?: string; @@ -14865,7 +14874,7 @@ declare namespace kendo.dataviz.ui { } interface StockChartValueAxisItem { - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; background?: string; color?: string; labels?: StockChartValueAxisItemLabels; @@ -15106,14 +15115,14 @@ declare namespace kendo.dataviz.ui { interface TreeMapOptions { name?: string; - dataSource?: any|any|kendo.data.HierarchicalDataSource; + dataSource?: any | any | kendo.data.HierarchicalDataSource; autoBind?: boolean; type?: string; theme?: string; valueField?: string; colorField?: string; textField?: string; - template?: string|Function; + template?: string | Function; colors?: any; itemCreated?(e: TreeMapItemCreatedEvent): void; dataBound?(e: TreeMapDataBoundEvent): void; @@ -15125,7 +15134,7 @@ declare namespace kendo.dataviz.ui { } interface TreeMapItemCreatedEvent extends TreeMapEvent { - element?: JQuery|Element; + element?: JQuery | Element; } interface TreeMapDataBoundEvent extends TreeMapEvent { @@ -15170,7 +15179,7 @@ declare namespace kendo.dataviz.map { nw: kendo.dataviz.map.Location; se: kendo.dataviz.map.Location; - constructor(nw: kendo.dataviz.map.Location|any, se: kendo.dataviz.map.Location|any); + constructor(nw: kendo.dataviz.map.Location | any, se: kendo.dataviz.map.Location | any); static create(a: kendo.dataviz.map.Location, b?: kendo.dataviz.map.Location): kendo.dataviz.map.Extent; static create(a: kendo.dataviz.map.Location, b?: any): kendo.dataviz.map.Extent; @@ -15310,7 +15319,7 @@ declare namespace kendo.dataviz.map { interface MarkerOptions { name?: string; - location?: any|kendo.dataviz.map.Location; + location?: any | kendo.dataviz.map.Location; shape?: string; title?: string; tooltip?: MarkerTooltip; @@ -15538,7 +15547,7 @@ declare namespace kendo.dataviz.diagram { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string|Function; + template?: string | Function; text?: string; visual?: Function; } @@ -16235,7 +16244,7 @@ declare namespace kendo.dataviz.diagram { interface ShapeOptions { name?: string; id?: string; - editable?: boolean|ShapeEditable; + editable?: boolean | ShapeEditable; path?: string; stroke?: ShapeStroke; type?: string; @@ -16335,10 +16344,10 @@ declare namespace kendo { namespace drawing { function align(elements: any, rect: kendo.geometry.Rect, alignment: string): void; - function drawDOM(element: JQuery, options: any): JQueryPromise; - function exportImage(group: kendo.drawing.Group, options: any): JQueryPromise; - function exportPDF(group: kendo.drawing.Group, options: kendo.drawing.PDFOptions): JQueryPromise; - function exportSVG(group: kendo.drawing.Group, options: any): JQueryPromise; + function drawDOM(element: JQuery, options?: any): JQueryPromise; + function exportImage(group: kendo.drawing.Group, options?: any): JQueryPromise; + function exportPDF(group: kendo.drawing.Group, options?: kendo.drawing.PDFOptions): JQueryPromise; + function exportSVG(group: kendo.drawing.Group, options?: any): JQueryPromise; function fit(element: kendo.drawing.Element, rect: kendo.geometry.Rect): void; function stack(elements: any): void; function vAlign(elements: any, rect: kendo.geometry.Rect, alignment: string): void; @@ -16354,40 +16363,40 @@ declare namespace kendo { function transformOrigin(firstElement: HTMLElement, secondElement: HTMLElement): any; } - function antiForgeryTokens(): any; - function bind(element: string, viewModel: any, namespace?: any): void; - function bind(element: string, viewModel: kendo.data.ObservableObject, namespace?: any): void; - function bind(element: JQuery, viewModel: any, namespace?: any): void; - function bind(element: JQuery, viewModel: kendo.data.ObservableObject, namespace?: any): void; - function bind(element: Element, viewModel: any, namespace?: any): void; - function bind(element: Element, viewModel: kendo.data.ObservableObject, namespace?: any): void; - function observableHierarchy(array: any): void; - function culture(culture: string): void; - function destroy(element: string): void; - function destroy(element: JQuery): void; - function destroy(element: Element): void; - function htmlEncode(value: string): string; - function parseDate(value: string, formats?: string, culture?: string): Date; - function parseDate(value: string, formats?: any, culture?: string): Date; - function parseFloat(value: string, culture?: string): number; - function parseInt(value: string, culture?: string): number; - function parseColor(color: string, noerror: boolean): kendo.Color; - function proxyModelSetters(): void; - function proxyModelSetters(data: kendo.data.Model): void; - function resize(element: string, force: boolean): void; - function resize(element: JQuery, force: boolean): void; - function resize(element: Element, force: boolean): void; - function saveAs(options: any): void; - function stringify(value: any): string; - function throttle(fn: Function, timeout: number): void; - function touchScroller(element: string): void; - function touchScroller(element: JQuery): void; - function touchScroller(element: Element): void; - function toString(value: Date, format: string, culture?: string): string; - function toString(value: number, format: string, culture?: string): string; - function unbind(element: string): void; - function unbind(element: JQuery): void; - function unbind(element: Element): void; + function antiForgeryTokens(): any; + function bind(element: string, viewModel: any, namespace?: any): void; + function bind(element: string, viewModel: kendo.data.ObservableObject, namespace?: any): void; + function bind(element: JQuery, viewModel: any, namespace?: any): void; + function bind(element: JQuery, viewModel: kendo.data.ObservableObject, namespace?: any): void; + function bind(element: Element, viewModel: any, namespace?: any): void; + function bind(element: Element, viewModel: kendo.data.ObservableObject, namespace?: any): void; + function observableHierarchy(array: any): void; + function culture(culture: string): void; + function destroy(element: string): void; + function destroy(element: JQuery): void; + function destroy(element: Element): void; + function htmlEncode(value: string): string; + function parseDate(value: string, formats?: string, culture?: string): Date; + function parseDate(value: string, formats?: any, culture?: string): Date; + function parseFloat(value: string, culture?: string): number; + function parseInt(value: string, culture?: string): number; + function parseColor(color: string, noerror: boolean): kendo.Color; + function proxyModelSetters(): void; + function proxyModelSetters(data: kendo.data.Model): void; + function resize(element: string, force: boolean): void; + function resize(element: JQuery, force: boolean): void; + function resize(element: Element, force: boolean): void; + function saveAs(options: any): void; + function stringify(value: any): string; + function throttle(fn: Function, timeout: number): void; + function touchScroller(element: string): void; + function touchScroller(element: JQuery): void; + function touchScroller(element: Element): void; + function toString(value: Date, format: string, culture?: string): string; + function toString(value: number, format: string, culture?: string): string; + function unbind(element: string): void; + function unbind(element: JQuery): void; + function unbind(element: Element): void; namespace pdf { function defineFont(map: any): void; @@ -16639,9 +16648,9 @@ declare namespace kendo.mobile.ui { } interface ActionSheetPopup { - direction?: number|string; - height?: number|string; - width?: number|string; + direction?: number | string; + height?: number | string; + width?: number | string; } interface ActionSheetOptions { @@ -17009,18 +17018,18 @@ declare namespace kendo.mobile.ui { name?: string; appendOnRefresh?: boolean; autoBind?: boolean; - dataSource?: kendo.data.DataSource|any; + dataSource?: kendo.data.DataSource | any; endlessScroll?: boolean; fixedHeaders?: boolean; - headerTemplate?: string|Function; + headerTemplate?: string | Function; loadMore?: boolean; messages?: ListViewMessages; pullToRefresh?: boolean; pullParameters?: Function; style?: string; - template?: string|Function; + template?: string | Function; type?: string; - filterable?: boolean|ListViewFilterable; + filterable?: boolean | ListViewFilterable; virtualViewSize?: number; click?(e: ListViewClickEvent): void; dataBound?(e: ListViewEvent): void; @@ -17232,8 +17241,8 @@ declare namespace kendo.mobile.ui { } interface PopOverPopup { - height?: number|string; - width?: number|string; + height?: number | string; + width?: number | string; } interface PopOverOptions { @@ -17289,8 +17298,8 @@ declare namespace kendo.mobile.ui { name?: string; autoBind?: boolean; bounceVelocityThreshold?: number; - contentHeight?: number|string; - dataSource?: kendo.data.DataSource|any; + contentHeight?: number | string; + dataSource?: kendo.data.DataSource | any; duration?: number; emptyTemplate?: string; enablePager?: boolean; @@ -17669,7 +17678,7 @@ declare namespace kendo.ooxml { wrap?: boolean; vAlign?: string; verticalAlign?: string; - value?: Date|number|string|boolean; + value?: Date | number | string | boolean; } interface WorkbookSheetRow { @@ -17875,7 +17884,7 @@ declare namespace kendo.dataviz.geometry { origin: kendo.geometry.Point; size: kendo.geometry.Size; - constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); + constructor(origin: kendo.geometry.Point | any, size: kendo.geometry.Size | any); static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; @@ -18101,7 +18110,7 @@ declare namespace kendo.dataviz.drawing { } - interface FillOptions { + interface FillOptions { @@ -18400,7 +18409,7 @@ declare namespace kendo.dataviz.drawing { } - interface PDFOptions { + interface PDFOptions { @@ -18504,7 +18513,7 @@ declare namespace kendo.dataviz.drawing { interface RadialGradientOptions { name?: string; - center?: any|kendo.geometry.Point; + center?: any | kendo.geometry.Point; radius?: number; stops?: any; } @@ -18588,7 +18597,7 @@ declare namespace kendo.dataviz.drawing { } - interface StrokeOptions { + interface StrokeOptions { @@ -18642,8 +18651,8 @@ declare namespace kendo.dataviz.drawing { } interface SurfaceTooltip { - animation?: boolean|SurfaceTooltipAnimation; - appendTo?: string|JQuery; + animation?: boolean | SurfaceTooltipAnimation; + appendTo?: string | JQuery; } interface SurfaceOptions { @@ -18738,20 +18747,20 @@ declare namespace kendo.dataviz.drawing { } - interface TooltipOptions { + interface TooltipOptions { autoHide?: boolean; - content?: string|Function; + content?: string | Function; position?: string; - height?: number|string; + height?: number | string; hideDelay?: number; offset?: number; shared?: boolean; showAfter?: number; showOn?: string; - width?: number|string; + width?: number | string; From fdb47e573f9c4d593094069136c1f12a0c17edd4 Mon Sep 17 00:00:00 2001 From: Gayan Ranasinghe Date: Mon, 4 Jul 2016 16:22:02 +0530 Subject: [PATCH 012/564] jquery reference --- kendo-ui/kendo-ui.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index b8aea8a61a..9d99d0bbfe 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -2,7 +2,7 @@ // Project: http://www.telerik.com/kendo-ui // Definitions by: Telerik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +/// declare namespace kendo { From 96817eace15d945f7202b8dc6ba00f4b7fe5f5dd Mon Sep 17 00:00:00 2001 From: Gayan Ranasinghe Date: Mon, 4 Jul 2016 16:27:55 +0530 Subject: [PATCH 013/564] removed implicitly has an 'any' type --- kendo-ui/kendo-ui.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index 9d99d0bbfe..9974c78775 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -511,7 +511,6 @@ declare namespace kendo.data { } module binders { } - export var binders; interface Bindings { [key: string]: Binding; From 679c3b36fe6ff78e323f0940b6e7c170acdfbc1b Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 08:48:05 -0400 Subject: [PATCH 014/564] 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 015/564] 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 016/564] 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 017/564] 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 018/564] 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 019/564] 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 020/564] 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 021/564] 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 022/564] 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 023/564] 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 950ce5c6c168a26b1e18ea0aa9f9354a27ccaaf9 Mon Sep 17 00:00:00 2001 From: Gayan Ranasinghe Date: Mon, 25 Jul 2016 10:22:19 +0530 Subject: [PATCH 024/564] remove formatting --- kendo-ui/kendo-ui.d.ts | 1302 ++++++++++++++++++++-------------------- 1 file changed, 651 insertions(+), 651 deletions(-) diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index 6fd787863f..941a432d81 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -2,6 +2,7 @@ // Project: http://www.telerik.com/kendo-ui // Definitions by: Telerik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + /// @@ -302,7 +303,7 @@ declare namespace kendo { } class ViewContainer extends Observable { - view: View; + view: View; } class Layout extends View { @@ -573,7 +574,6 @@ declare namespace kendo.data { isAllDay?: boolean; id?: any; start?: Date; - ownerId?: number; taskId?: number; startTimezone?: string; recurrenceId?: any; @@ -587,7 +587,6 @@ declare namespace kendo.data { static fields: DataSourceSchemaModelFields; constructor(data?: SchedulerEventData); - ownerId: number; taskId: number; description: string; end: Date; @@ -844,7 +843,7 @@ declare namespace kendo.data { columns: PivotSchemaColumnAxis; } - interface PivotSchema extends DataSourceSchema { + interface PivotSchema extends DataSourceSchema{ axes?: any; catalogs?: any; cubes?: any; @@ -953,7 +952,7 @@ declare namespace kendo.data { } interface DataSourceSchemaWithConstructorModel extends DataSourceSchema { - model?: typeof Model; + model?: typeof Model; } interface DataSourceSchemaModel { @@ -1001,7 +1000,7 @@ declare namespace kendo.data { every(callback: (item: Object, index: number, source: ObservableArray) => boolean): boolean; filter(callback: (item: Object, index: number, source: ObservableArray) => boolean): any[]; find(callback: (item: Object, index: number, source: ObservableArray) => boolean): any; - forEach(callback: (item: Object, index: number, source: ObservableArray) => void): void; + forEach(callback: (item: Object, index: number, source: ObservableArray) => void ): void; indexOf(item: any): number; join(separator: string): string; map(callback: (item: Object, index: number, source: ObservableArray) => any): any[]; @@ -1027,7 +1026,7 @@ declare namespace kendo.data { items?: kendo.data.Model[]; } - class DataSource extends Observable { + class DataSource extends Observable{ options: DataSourceOptions; static create(options?: DataSourceOptions): DataSource; @@ -1247,7 +1246,7 @@ declare namespace kendo.data { sort?: any; transport?: DataSourceTransport; type?: string; - change?(e: DataSourceChangeEvent): void; + change? (e: DataSourceChangeEvent): void; error?(e: DataSourceErrorEvent): void; sync?(e: DataSourceEvent): void; requestStart?(e: DataSourceRequestStartEvent): void; @@ -1330,7 +1329,7 @@ declare namespace kendo.ui { function plugin(widget: typeof kendo.ui.Widget, register?: typeof kendo.dataviz.ui, prefix?: String): void; function plugin(widget: any, register?: typeof kendo.dataviz.ui, prefix?: String): void; - class Draggable extends kendo.ui.Widget { + class Draggable extends kendo.ui.Widget{ element: JQuery; currentTarget: JQuery; constructor(element: Element, options?: DraggableOptions); @@ -1341,7 +1340,7 @@ declare namespace kendo.ui { sender?: Draggable; } - class DropTarget extends kendo.ui.Widget { + class DropTarget extends kendo.ui.Widget{ element: JQuery; constructor(element: Element, options?: DropTargetOptions); options: DropTargetOptions; @@ -1371,7 +1370,7 @@ declare namespace kendo.ui { draggable?: kendo.ui.Draggable; } - class DropTargetArea extends kendo.ui.Widget { + class DropTargetArea extends kendo.ui.Widget{ element: JQuery; constructor(element: Element, options?: DropTargetAreaOptions); options: DropTargetAreaOptions; @@ -1522,7 +1521,7 @@ declare namespace kendo.dataviz.map.layer { declare namespace kendo.drawing.pdf { function saveAs(group: kendo.drawing.Group, fileName: string, - proxyUrl?: string, callback?: Function): void; + proxyUrl?: string, callback?: Function): void; } declare namespace kendo.geometry { @@ -1695,7 +1694,7 @@ declare namespace kendo.geometry { origin: kendo.geometry.Point; size: kendo.geometry.Size; - constructor(origin: kendo.geometry.Point | any, size: kendo.geometry.Size | any); + constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; @@ -1921,7 +1920,7 @@ declare namespace kendo.drawing { } - interface FillOptions { + interface FillOptions { @@ -2220,7 +2219,7 @@ declare namespace kendo.drawing { } - interface PDFOptions { + interface PDFOptions { @@ -2324,7 +2323,7 @@ declare namespace kendo.drawing { interface RadialGradientOptions { name?: string; - center?: any | kendo.geometry.Point; + center?: any|kendo.geometry.Point; radius?: number; stops?: any; } @@ -2408,7 +2407,7 @@ declare namespace kendo.drawing { } - interface StrokeOptions { + interface StrokeOptions { @@ -2462,8 +2461,8 @@ declare namespace kendo.drawing { } interface SurfaceTooltip { - animation?: boolean | SurfaceTooltipAnimation; - appendTo?: string | JQuery; + animation?: boolean|SurfaceTooltipAnimation; + appendTo?: string|JQuery; } interface SurfaceOptions { @@ -2558,20 +2557,20 @@ declare namespace kendo.drawing { } - interface TooltipOptions { + interface TooltipOptions { autoHide?: boolean; - content?: string | Function; + content?: string|Function; position?: string; - height?: number | string; + height?: number|string; hideDelay?: number; offset?: number; shared?: boolean; showAfter?: number; showOn?: string; - width?: number | string; + width?: number|string; @@ -2641,14 +2640,14 @@ declare namespace kendo.ui { interface AutoCompleteOptions { name?: string; - animation?: boolean | AutoCompleteAnimation; - dataSource?: any | any | kendo.data.DataSource; + animation?: boolean|AutoCompleteAnimation; + dataSource?: any|any|kendo.data.DataSource; dataTextField?: string; delay?: number; enable?: boolean; filter?: string; - fixedGroupTemplate?: string | Function; - groupTemplate?: string | Function; + fixedGroupTemplate?: string|Function; + groupTemplate?: string|Function; height?: number; highlightFirst?: boolean; ignoreCase?: boolean; @@ -2657,11 +2656,11 @@ declare namespace kendo.ui { popup?: any; separator?: string; suggest?: boolean; - value?: any; + headerTemplate?: string|Function; headerTemplate?: string | Function; template?: string | Function; valuePrimitive?: boolean; - virtual?: boolean | AutoCompleteVirtual; + virtual?: boolean|AutoCompleteVirtual; change?(e: AutoCompleteChangeEvent): void; close?(e: AutoCompleteCloseEvent): void; dataBound?(e: AutoCompleteDataBoundEvent): void; @@ -2779,8 +2778,8 @@ declare namespace kendo.ui { culture?: string; dates?: any; depth?: string; - disableDates?: any | Function; - footer?: string | Function; + disableDates?: any|Function; + footer?: string|Function; format?: string; max?: Date; min?: Date; @@ -2827,7 +2826,7 @@ declare namespace kendo.ui { interface ColorPaletteOptions { name?: string; - palette?: string | any; + palette?: string|any; columns?: number; tileSize?: ColorPaletteTileSize; value?: string; @@ -2882,7 +2881,7 @@ declare namespace kendo.ui { columns?: number; tileSize?: ColorPickerTileSize; messages?: ColorPickerMessages; - palette?: string | any; + palette?: string|any; opacity?: boolean; preview?: boolean; toolIcon?: string; @@ -2982,14 +2981,14 @@ declare namespace kendo.ui { autoBind?: boolean; cascadeFrom?: string; cascadeFromField?: string; - dataSource?: any | any | kendo.data.DataSource; + dataSource?: any|any|kendo.data.DataSource; dataTextField?: string; dataValueField?: string; delay?: number; enable?: boolean; filter?: string; - fixedGroupTemplate?: string | Function; - groupTemplate?: string | Function; + fixedGroupTemplate?: string|Function; + groupTemplate?: string|Function; height?: number; highlightFirst?: boolean; ignoreCase?: boolean; @@ -2998,12 +2997,12 @@ declare namespace kendo.ui { placeholder?: string; popup?: ComboBoxPopup; suggest?: boolean; - headerTemplate?: string | Function; - template?: string | Function; + headerTemplate?: string|Function; + template?: string|Function; text?: string; value?: string; valuePrimitive?: boolean; - virtual?: boolean | ComboBoxVirtual; + virtual?: boolean|ComboBoxVirtual; change?(e: ComboBoxChangeEvent): void; close?(e: ComboBoxCloseEvent): void; dataBound?(e: ComboBoxDataBoundEvent): void; @@ -3098,16 +3097,16 @@ declare namespace kendo.ui { interface ContextMenuOptions { name?: string; alignToAnchor?: boolean; - animation?: boolean | ContextMenuAnimation; + animation?: boolean|ContextMenuAnimation; closeOnClick?: boolean; - dataSource?: any | any; + dataSource?: any|any; direction?: string; filter?: string; hoverDelay?: number; orientation?: string; popupCollision?: string; showOn?: string; - target?: string | JQuery; + target?: string|JQuery; close?(e: ContextMenuCloseEvent): void; open?(e: ContextMenuOpenEvent): void; activate?(e: ContextMenuActivateEvent): void; @@ -3208,13 +3207,13 @@ declare namespace kendo.ui { interface DatePickerOptions { name?: string; - animation?: boolean | DatePickerAnimation; + animation?: boolean|DatePickerAnimation; ARIATemplate?: string; culture?: string; dates?: any; depth?: string; - disableDates?: any | Function; - footer?: string | Function; + disableDates?: any|Function; + footer?: string|Function; format?: string; max?: Date; min?: Date; @@ -3298,12 +3297,12 @@ declare namespace kendo.ui { interface DateTimePickerOptions { name?: string; - animation?: boolean | DateTimePickerAnimation; + animation?: boolean|DateTimePickerAnimation; ARIATemplate?: string; culture?: string; dates?: any; depth?: string; - disableDates?: any | Function; + disableDates?: any|Function; footer?: string; format?: string; interval?: number; @@ -3409,32 +3408,32 @@ declare namespace kendo.ui { interface DropDownListOptions { name?: string; - animation?: boolean | DropDownListAnimation; + animation?: boolean|DropDownListAnimation; autoBind?: boolean; cascadeFrom?: string; cascadeFromField?: string; - dataSource?: any | any | kendo.data.DataSource; + dataSource?: any|any|kendo.data.DataSource; dataTextField?: string; dataValueField?: string; delay?: number; enable?: boolean; filter?: string; - fixedGroupTemplate?: string | Function; - groupTemplate?: string | Function; + fixedGroupTemplate?: string|Function; + groupTemplate?: string|Function; height?: number; ignoreCase?: boolean; index?: number; minLength?: number; popup?: DropDownListPopup; - optionLabel?: string | any; - optionLabelTemplate?: string | Function; - headerTemplate?: string | Function; - template?: string | Function; - valueTemplate?: string | Function; + optionLabel?: string|any; + optionLabelTemplate?: string|Function; + headerTemplate?: string|Function; + template?: string|Function; + valueTemplate?: string|Function; text?: string; value?: string; valuePrimitive?: boolean; - virtual?: boolean | DropDownListVirtual; + virtual?: boolean|DropDownListVirtual; change?(e: DropDownListChangeEvent): void; close?(e: DropDownListCloseEvent): void; dataBound?(e: DropDownListDataBoundEvent): void; @@ -3556,32 +3555,32 @@ declare namespace kendo.ui { interface EditorFileBrowserTransportCreate { contentType?: string; - data?: any | string | Function; + data?: any|string|Function; dataType?: string; type?: string; - url?: string | Function; + url?: string|Function; } interface EditorFileBrowserTransportDestroy { contentType?: string; - data?: any | string | Function; + data?: any|string|Function; dataType?: string; type?: string; - url?: string | Function; + url?: string|Function; } interface EditorFileBrowserTransportRead { contentType?: string; - data?: any | string | Function; + data?: any|string|Function; dataType?: string; type?: string; - url?: string | Function; + url?: string|Function; } interface EditorFileBrowserTransport { read?: EditorFileBrowserTransportRead; uploadUrl?: string; - fileUrl?: string | Function; + fileUrl?: string|Function; destroy?: EditorFileBrowserTransportDestroy; create?: EditorFileBrowserTransportCreate; } @@ -3638,33 +3637,33 @@ declare namespace kendo.ui { interface EditorImageBrowserTransportCreate { contentType?: string; - data?: any | string | Function; + data?: any|string|Function; dataType?: string; type?: string; - url?: string | Function; + url?: string|Function; } interface EditorImageBrowserTransportDestroy { contentType?: string; - data?: any | string | Function; + data?: any|string|Function; dataType?: string; type?: string; - url?: string | Function; + url?: string|Function; } interface EditorImageBrowserTransportRead { contentType?: string; - data?: any | string | Function; + data?: any|string|Function; dataType?: string; type?: string; - url?: string | Function; + url?: string|Function; } interface EditorImageBrowserTransport { read?: EditorImageBrowserTransportRead; - thumbnailUrl?: string | Function; + thumbnailUrl?: string|Function; uploadUrl?: string; - imageUrl?: string | Function; + imageUrl?: string|Function; destroy?: EditorImageBrowserTransportDestroy; create?: EditorImageBrowserTransportCreate; } @@ -3753,15 +3752,15 @@ declare namespace kendo.ui { } interface EditorPdfMargin { - bottom?: number | string; - left?: number | string; - right?: number | string; - top?: number | string; + bottom?: number|string; + left?: number|string; + right?: number|string; + top?: number|string; } interface EditorPdf { author?: string; - avoidLinks?: boolean | string; + avoidLinks?: boolean|string; creator?: string; date?: Date; fileName?: string; @@ -3769,7 +3768,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: EditorPdfMargin; - paperSize?: string | any; + paperSize?: string|any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -3820,7 +3819,7 @@ declare namespace kendo.ui { messages?: EditorMessages; pasteCleanup?: EditorPasteCleanup; pdf?: EditorPdf; - resizable?: boolean | EditorResizable; + resizable?: boolean|EditorResizable; serialization?: EditorSerialization; stylesheets?: any; tools?: EditorTool[]; @@ -3936,7 +3935,7 @@ declare namespace kendo.ui { interface FilterMenuOptions { name?: string; - dataSource?: any | any | kendo.data.DataSource; + dataSource?: any|any|kendo.data.DataSource; extra?: boolean; field?: string; messages?: FilterMenuMessages; @@ -4040,7 +4039,7 @@ declare namespace kendo.ui { } interface GanttAssignments { - dataSource?: any | any | kendo.data.DataSource; + dataSource?: any|any|kendo.data.DataSource; dataResourceIdField?: string; dataTaskIdField?: string; dataValueField?: string; @@ -4050,7 +4049,7 @@ declare namespace kendo.ui { field?: string; title?: string; format?: string; - width?: string | number; + width?: string|number; editable?: boolean; sortable?: boolean; } @@ -4061,7 +4060,7 @@ declare namespace kendo.ui { interface GanttEditable { confirmation?: boolean; - template?: string | Function; + template?: string|Function; } interface GanttMessagesActions { @@ -4108,15 +4107,15 @@ declare namespace kendo.ui { } interface GanttPdfMargin { - bottom?: number | string; - left?: number | string; - right?: number | string; - top?: number | string; + bottom?: number|string; + left?: number|string; + right?: number|string; + top?: number|string; } interface GanttPdf { author?: string; - avoidLinks?: boolean | string; + avoidLinks?: boolean|string; creator?: string; date?: Date; fileName?: string; @@ -4124,7 +4123,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: GanttPdfMargin; - paperSize?: string | any; + paperSize?: string|any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -4134,31 +4133,31 @@ declare namespace kendo.ui { interface GanttResources { dataFormatField?: string; dataColorField?: string; - dataSource?: any | any | kendo.data.DataSource; + dataSource?: any|any|kendo.data.DataSource; dataTextField?: string; field?: string; } interface GanttToolbarItem { name?: string; - template?: string | Function; + template?: string|Function; text?: string; } interface GanttTooltip { - template?: string | Function; + template?: string|Function; visible?: boolean; } interface GanttView { type?: string; selected?: boolean; - slotSize?: number | string; - timeHeaderTemplate?: string | Function; - dayHeaderTemplate?: string | Function; - weekHeaderTemplate?: string | Function; - monthHeaderTemplate?: string | Function; - yearHeaderTemplate?: string | Function; + slotSize?: number|string; + timeHeaderTemplate?: string|Function; + dayHeaderTemplate?: string|Function; + weekHeaderTemplate?: string|Function; + monthHeaderTemplate?: string|Function; + yearHeaderTemplate?: string|Function; resizeTooltipFormat?: string; } @@ -4168,10 +4167,10 @@ declare namespace kendo.ui { autoBind?: boolean; columnResizeHandleWidth?: number; columns?: GanttColumn[]; - currentTimeMarker?: boolean | GanttCurrentTimeMarker; - dataSource?: any | any | kendo.data.GanttDataSource; - dependencies?: any | any | kendo.data.GanttDependencyDataSource; - editable?: boolean | GanttEditable; + currentTimeMarker?: boolean|GanttCurrentTimeMarker; + dataSource?: any|any|kendo.data.GanttDataSource; + dependencies?: any|any|kendo.data.GanttDependencyDataSource; + editable?: boolean|GanttEditable; navigatable?: boolean; workDayStart?: Date; workDayEnd?: Date; @@ -4179,20 +4178,20 @@ declare namespace kendo.ui { workWeekEnd?: number; hourSpan?: number; snap?: boolean; - height?: number | string; - listWidth?: string | number; + height?: number|string; + listWidth?: string|number; messages?: GanttMessages; pdf?: GanttPdf; resizable?: boolean; selectable?: boolean; showWorkDays?: boolean; showWorkHours?: boolean; - taskTemplate?: string | Function; + taskTemplate?: string|Function; toolbar?: GanttToolbarItem[]; tooltip?: GanttTooltip; views?: GanttView[]; resources?: GanttResources; - rowHeight?: number | string; + rowHeight?: number|string; dataBinding?(e: GanttDataBindingEvent): void; dataBound?(e: GanttDataBoundEvent): void; add?(e: GanttAddEvent): void; @@ -4386,7 +4385,7 @@ declare namespace kendo.ui { } interface GridAllowCopy { - delimeter?: string | any; + delimeter?: string|any; } interface GridColumnMenuMessages { @@ -4423,7 +4422,7 @@ declare namespace kendo.ui { } interface GridColumnFilterableCell { - dataSource?: any | kendo.data.DataSource; + dataSource?: any|kendo.data.DataSource; dataTextField?: string; delay?: number; inputWidth?: number; @@ -4438,13 +4437,13 @@ declare namespace kendo.ui { interface GridColumnFilterable { cell?: GridColumnFilterableCell; multi?: boolean; - dataSource?: any | any | kendo.data.DataSource; + dataSource?: any|any|kendo.data.DataSource; checkAll?: boolean; itemTemplate?: Function; operators?: any; search?: boolean; ignoreCase?: boolean; - ui?: string | Function; + ui?: string|Function; } interface GridColumnSortable { @@ -4458,36 +4457,36 @@ declare namespace kendo.ui { command?: GridColumnCommandItem[]; encoded?: boolean; field?: string; - filterable?: boolean | GridColumnFilterable; + filterable?: boolean|GridColumnFilterable; footerAttributes?: any; - footerTemplate?: string | Function; + footerTemplate?: string|Function; format?: string; groupable?: boolean; - groupHeaderTemplate?: string | Function; - groupFooterTemplate?: string | Function; + groupHeaderTemplate?: string|Function; + groupFooterTemplate?: string|Function; headerAttributes?: any; - headerTemplate?: string | Function; + headerTemplate?: string|Function; hidden?: boolean; locked?: boolean; lockable?: boolean; minScreenWidth?: number; - sortable?: boolean | GridColumnSortable; - template?: string | Function; + sortable?: boolean|GridColumnSortable; + template?: string|Function; title?: string; - width?: string | number; + width?: string|number; values?: any; menu?: boolean; type?: any; } interface GridEditable { - confirmation?: boolean | string | Function; + confirmation?: boolean|string|Function; cancelDelete?: string; confirmDelete?: string; createAt?: string; destroy?: boolean; mode?: string; - template?: string | Function; + template?: string|Function; update?: boolean; window?: any; } @@ -4600,7 +4599,7 @@ declare namespace kendo.ui { } interface GridNoRecords { - template?: string | Function; + template?: string|Function; } interface GridPageableMessages { @@ -4623,23 +4622,23 @@ declare namespace kendo.ui { numeric?: boolean; buttonCount?: number; input?: boolean; - pageSizes?: boolean | any; + pageSizes?: boolean|any; refresh?: boolean; info?: boolean; messages?: GridPageableMessages; } interface GridPdfMargin { - bottom?: number | string; - left?: number | string; - right?: number | string; - top?: number | string; + bottom?: number|string; + left?: number|string; + right?: number|string; + top?: number|string; } interface GridPdf { allPages?: boolean; author?: string; - avoidLinks?: boolean | string; + avoidLinks?: boolean|string; creator?: string; date?: Date; fileName?: string; @@ -4647,7 +4646,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: GridPdfMargin; - paperSize?: string | any; + paperSize?: string|any; template?: string; repeatHeaders?: boolean; scale?: number; @@ -4668,38 +4667,38 @@ declare namespace kendo.ui { interface GridToolbarItem { name?: string; - template?: string | Function; + template?: string|Function; text?: string; } interface GridOptions { name?: string; - allowCopy?: boolean | GridAllowCopy; - altRowTemplate?: string | Function; + allowCopy?: boolean|GridAllowCopy; + altRowTemplate?: string|Function; autoBind?: boolean; columnResizeHandleWidth?: number; columns?: GridColumn[]; - columnMenu?: boolean | GridColumnMenu; - dataSource?: any | any | kendo.data.DataSource; - detailTemplate?: string | Function; - editable?: boolean | GridEditable; + columnMenu?: boolean|GridColumnMenu; + dataSource?: any|any|kendo.data.DataSource; + detailTemplate?: string|Function; + editable?: boolean|GridEditable; excel?: GridExcel; - filterable?: boolean | GridFilterable; - groupable?: boolean | GridGroupable; - height?: number | string; + filterable?: boolean|GridFilterable; + groupable?: boolean|GridGroupable; + height?: number|string; messages?: GridMessages; - mobile?: boolean | string; + mobile?: boolean|string; navigatable?: boolean; - noRecords?: boolean | GridNoRecords; - pageable?: boolean | GridPageable; + noRecords?: boolean|GridNoRecords; + pageable?: boolean|GridPageable; pdf?: GridPdf; reorderable?: boolean; resizable?: boolean; - rowTemplate?: string | Function; - scrollable?: boolean | GridScrollable; - selectable?: boolean | string; - sortable?: boolean | GridSortable; - toolbar?: string | ((...args: any[]) => string) | GridToolbarItem[]; + rowTemplate?: string|Function; + scrollable?: boolean|GridScrollable; + selectable?: boolean|string; + sortable?: boolean|GridSortable; + toolbar?: string | ((...args:any[]) => string) | GridToolbarItem[]; cancel?(e: GridCancelEvent): void; change?(e: GridChangeEvent): void; columnHide?(e: GridColumnHideEvent): void; @@ -4873,10 +4872,10 @@ declare namespace kendo.ui { interface ListViewOptions { name?: string; autoBind?: boolean; - dataSource?: any | any | kendo.data.DataSource; + dataSource?: any|any|kendo.data.DataSource; editTemplate?: Function; navigatable?: boolean; - selectable?: boolean | string; + selectable?: boolean|string; template?: Function; altTemplate?: Function; cancel?(e: ListViewCancelEvent): void; @@ -5015,9 +5014,9 @@ declare namespace kendo.ui { interface MenuOptions { name?: string; - animation?: boolean | MenuAnimation; + animation?: boolean|MenuAnimation; closeOnClick?: boolean; - dataSource?: any | any; + dataSource?: any|any; direction?: string; hoverDelay?: number; openOnClick?: boolean; @@ -5122,17 +5121,17 @@ declare namespace kendo.ui { interface MultiSelectOptions { name?: string; - animation?: boolean | MultiSelectAnimation; + animation?: boolean|MultiSelectAnimation; autoBind?: boolean; autoClose?: boolean; - dataSource?: any | any | kendo.data.DataSource; + dataSource?: any|any|kendo.data.DataSource; dataTextField?: string; dataValueField?: string; delay?: number; enable?: boolean; filter?: string; - fixedGroupTemplate?: string | Function; - groupTemplate?: string | Function; + fixedGroupTemplate?: string|Function; + groupTemplate?: string|Function; height?: number; highlightFirst?: boolean; ignoreCase?: boolean; @@ -5140,13 +5139,13 @@ declare namespace kendo.ui { maxSelectedItems?: number; placeholder?: string; popup?: MultiSelectPopup; - headerTemplate?: string | Function; - itemTemplate?: string | Function; + headerTemplate?: string|Function; + itemTemplate?: string|Function; tagTemplate?: string; tagMode?: string; value?: any; valuePrimitive?: boolean; - virtual?: boolean | MultiSelectVirtual; + virtual?: boolean|MultiSelectVirtual; change?(e: MultiSelectChangeEvent): void; close?(e: MultiSelectCloseEvent): void; dataBound?(e: MultiSelectDataBoundEvent): void; @@ -5235,16 +5234,16 @@ declare namespace kendo.ui { interface NotificationOptions { name?: string; allowHideAfter?: number; - animation?: any | boolean; - appendTo?: string | JQuery; + animation?: any|boolean; + appendTo?: string|JQuery; autoHideAfter?: number; button?: boolean; - height?: number | string; + height?: number|string; hideOnClick?: boolean; position?: NotificationPosition; stacking?: string; templates?: NotificationTemplate[]; - width?: number | string; + width?: number|string; hide?(e: NotificationHideEvent): void; show?(e: NotificationShowEvent): void; } @@ -5369,13 +5368,13 @@ declare namespace kendo.ui { name?: string; autoBind?: boolean; buttonCount?: number; - dataSource?: any | kendo.data.DataSource; + dataSource?: any|kendo.data.DataSource; selectTemplate?: string; linkTemplate?: string; info?: boolean; input?: boolean; numeric?: boolean; - pageSizes?: boolean | any; + pageSizes?: boolean|any; previousNext?: boolean; refresh?: boolean; messages?: PagerMessages; @@ -5483,9 +5482,9 @@ declare namespace kendo.ui { interface PanelBarOptions { name?: string; - animation?: boolean | PanelBarAnimation; + animation?: boolean|PanelBarAnimation; contentUrls?: any; - dataSource?: any | any; + dataSource?: any|any; expandMode?: string; activate?(e: PanelBarActivateEvent): void; collapse?(e: PanelBarCollapseEvent): void; @@ -5589,10 +5588,10 @@ declare namespace kendo.ui { interface PivotConfiguratorOptions { name?: string; - dataSource?: any | kendo.data.PivotDataSource; + dataSource?: any|kendo.data.PivotDataSource; filterable?: boolean; - sortable?: boolean | PivotConfiguratorSortable; - height?: number | string; + sortable?: boolean|PivotConfiguratorSortable; + height?: number|string; messages?: PivotConfiguratorMessages; } interface PivotConfiguratorEvent { @@ -5668,15 +5667,15 @@ declare namespace kendo.ui { } interface PivotGridPdfMargin { - bottom?: number | string; - left?: number | string; - right?: number | string; - top?: number | string; + bottom?: number|string; + left?: number|string; + right?: number|string; + top?: number|string; } interface PivotGridPdf { author?: string; - avoidLinks?: boolean | string; + avoidLinks?: boolean|string; creator?: string; date?: Date; fileName?: string; @@ -5684,7 +5683,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: PivotGridPdfMargin; - paperSize?: string | any; + paperSize?: string|any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -5697,20 +5696,20 @@ declare namespace kendo.ui { interface PivotGridOptions { name?: string; - dataSource?: any | kendo.data.PivotDataSource; + dataSource?: any|kendo.data.PivotDataSource; autoBind?: boolean; reorderable?: boolean; excel?: PivotGridExcel; pdf?: PivotGridPdf; filterable?: boolean; - sortable?: boolean | PivotGridSortable; + sortable?: boolean|PivotGridSortable; columnWidth?: number; - height?: number | string; - columnHeaderTemplate?: string | Function; - dataCellTemplate?: string | Function; - kpiStatusTemplate?: string | Function; - kpiTrendTemplate?: string | Function; - rowHeaderTemplate?: string | Function; + height?: number|string; + columnHeaderTemplate?: string|Function; + dataCellTemplate?: string|Function; + kpiStatusTemplate?: string|Function; + kpiTrendTemplate?: string|Function; + rowHeaderTemplate?: string|Function; messages?: PivotGridMessages; dataBinding?(e: PivotGridDataBindingEvent): void; dataBound?(e: PivotGridDataBoundEvent): void; @@ -5792,9 +5791,9 @@ declare namespace kendo.ui { interface PopupOptions { name?: string; adjustSize?: any; - animation?: boolean | PopupAnimation; - anchor?: string | JQuery; - appendTo?: string | JQuery; + animation?: boolean|PopupAnimation; + anchor?: string|JQuery; + appendTo?: string|JQuery; collision?: string; origin?: string; position?: string; @@ -6026,19 +6025,19 @@ declare namespace kendo.ui { } interface SchedulerEditable { - confirmation?: boolean | string; + confirmation?: boolean|string; create?: boolean; destroy?: boolean; editRecurringMode?: string; move?: boolean; resize?: boolean; - template?: string | Function; + template?: string|Function; update?: boolean; window?: any; } interface SchedulerFooter { - command?: string | boolean; + command?: string|boolean; } interface SchedulerGroup { @@ -6175,15 +6174,15 @@ declare namespace kendo.ui { } interface SchedulerPdfMargin { - bottom?: number | string; - left?: number | string; - right?: number | string; - top?: number | string; + bottom?: number|string; + left?: number|string; + right?: number|string; + top?: number|string; } interface SchedulerPdf { author?: string; - avoidLinks?: boolean | string; + avoidLinks?: boolean|string; creator?: string; date?: Date; fileName?: string; @@ -6191,7 +6190,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: SchedulerPdfMargin; - paperSize?: string | any; + paperSize?: string|any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -6200,7 +6199,7 @@ declare namespace kendo.ui { interface SchedulerResource { dataColorField?: string; - dataSource?: any | any | kendo.data.DataSource; + dataSource?: any|any|kendo.data.DataSource; dataTextField?: string; dataValueField?: string; field?: string; @@ -6225,26 +6224,26 @@ declare namespace kendo.ui { } interface SchedulerView { - allDayEventTemplate?: string | Function; + allDayEventTemplate?: string|Function; allDaySlot?: boolean; - allDaySlotTemplate?: string | Function; + allDaySlotTemplate?: string|Function; columnWidth?: number; - dateHeaderTemplate?: string | Function; - dayTemplate?: string | Function; - editable?: boolean | SchedulerViewEditable; + dateHeaderTemplate?: string|Function; + dayTemplate?: string|Function; + editable?: boolean|SchedulerViewEditable; endTime?: Date; eventHeight?: number; - eventTemplate?: string | Function; - eventTimeTemplate?: string | Function; + eventTemplate?: string|Function; + eventTimeTemplate?: string|Function; group?: SchedulerViewGroup; majorTick?: number; - majorTimeHeaderTemplate?: string | Function; + majorTimeHeaderTemplate?: string|Function; minorTickCount?: number; - minorTimeHeaderTemplate?: string | Function; + minorTimeHeaderTemplate?: string|Function; selected?: boolean; selectedDateFormat?: string; showWorkHours?: boolean; - slotTemplate?: string | Function; + slotTemplate?: string|Function; startTime?: Date; title?: string; type?: string; @@ -6262,27 +6261,27 @@ declare namespace kendo.ui { interface SchedulerOptions { name?: string; - allDayEventTemplate?: string | Function; + allDayEventTemplate?: string|Function; allDaySlot?: boolean; autoBind?: boolean; - currentTimeMarker?: boolean | SchedulerCurrentTimeMarker; - dataSource?: any | any | kendo.data.SchedulerDataSource; + currentTimeMarker?: boolean|SchedulerCurrentTimeMarker; + dataSource?: any|any|kendo.data.SchedulerDataSource; date?: Date; - dateHeaderTemplate?: string | Function; - editable?: boolean | SchedulerEditable; + dateHeaderTemplate?: string|Function; + editable?: boolean|SchedulerEditable; endTime?: Date; - eventTemplate?: string | Function; - footer?: boolean | SchedulerFooter; + eventTemplate?: string|Function; + footer?: boolean|SchedulerFooter; group?: SchedulerGroup; - height?: number | string; + height?: number|string; majorTick?: number; - majorTimeHeaderTemplate?: string | Function; + majorTimeHeaderTemplate?: string|Function; max?: Date; messages?: SchedulerMessages; min?: Date; minorTickCount?: number; - minorTimeHeaderTemplate?: string | Function; - mobile?: boolean | string; + minorTimeHeaderTemplate?: string|Function; + mobile?: boolean|string; pdf?: SchedulerPdf; resources?: SchedulerResource[]; selectable?: boolean; @@ -6292,8 +6291,8 @@ declare namespace kendo.ui { timezone?: string; toolbar?: SchedulerToolbarItem[]; views?: SchedulerView[]; - groupHeaderTemplate?: string | Function; - width?: number | string; + groupHeaderTemplate?: string|Function; + width?: number|string; workDayStart?: Date; workDayEnd?: Date; workWeekStart?: number; @@ -6489,17 +6488,17 @@ declare namespace kendo.ui { name?: string; axis?: string; autoScroll?: boolean; - container?: string | JQuery; + container?: string|JQuery; connectWith?: string; cursor?: string; cursorOffset?: SortableCursorOffset; disabled?: string; filter?: string; handler?: string; - hint?: Function | string | JQuery; + hint?: Function|string|JQuery; holdToDrag?: boolean; ignore?: string; - placeholder?: Function | string | JQuery; + placeholder?: Function|string|JQuery; start?(e: SortableStartEvent): void; move?(e: SortableMoveEvent): void; end?(e: SortableEndEvent): void; @@ -6686,10 +6685,10 @@ declare namespace kendo.ui { } interface SpreadsheetPdfMargin { - bottom?: number | string; - left?: number | string; - right?: number | string; - top?: number | string; + bottom?: number|string; + left?: number|string; + right?: number|string; + top?: number|string; } interface SpreadsheetPdf { @@ -6705,7 +6704,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: SpreadsheetPdfMargin; - paperSize?: string | any; + paperSize?: string|any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -6729,7 +6728,7 @@ declare namespace kendo.ui { index?: number; logic?: string; type?: string; - value?: number | string | Date; + value?: number|string|Date; values?: any; } @@ -6787,7 +6786,7 @@ declare namespace kendo.ui { link?: string; textAlign?: string; underline?: boolean; - value?: number | string | boolean | Date; + value?: number|string|boolean|Date; validation?: SpreadsheetSheetRowCellValidation; verticalAlign?: string; wrap?: boolean; @@ -6825,9 +6824,9 @@ declare namespace kendo.ui { } interface SpreadsheetToolbar { - home?: boolean | any; - insert?: boolean | any; - data?: boolean | any; + home?: boolean|any; + insert?: boolean|any; + data?: boolean|any; } interface SpreadsheetInsertSheetOptions { @@ -6854,7 +6853,7 @@ declare namespace kendo.ui { rows?: number; sheets?: SpreadsheetSheet[]; sheetsbar?: boolean; - toolbar?: boolean | SpreadsheetToolbar; + toolbar?: boolean|SpreadsheetToolbar; change?(e: SpreadsheetChangeEvent): void; render?(e: SpreadsheetRenderEvent): void; excelExport?(e: SpreadsheetExcelExportEvent): void; @@ -6880,7 +6879,7 @@ declare namespace kendo.ui { } interface SpreadsheetExcelImportEvent extends SpreadsheetEvent { - file?: Blob | File; + file?: Blob|File; progress?: JQueryPromise; } @@ -6980,18 +6979,18 @@ declare namespace kendo.ui { interface TabStripOptions { name?: string; - animation?: boolean | TabStripAnimation; + animation?: boolean|TabStripAnimation; collapsible?: boolean; contentUrls?: any; dataContentField?: string; dataContentUrlField?: string; dataImageUrlField?: string; - dataSource?: any | any | kendo.data.DataSource; + dataSource?: any|any|kendo.data.DataSource; dataSpriteCssClass?: string; dataTextField?: string; dataUrlField?: string; navigatable?: boolean; - scrollable?: boolean | TabStripScrollable; + scrollable?: boolean|TabStripScrollable; tabPosition?: string; value?: string; activate?(e: TabStripActivateEvent): void; @@ -7082,7 +7081,7 @@ declare namespace kendo.ui { interface TimePickerOptions { name?: string; - animation?: boolean | TimePickerAnimation; + animation?: boolean|TimePickerAnimation; culture?: string; dates?: any; format?: string; @@ -7188,13 +7187,13 @@ declare namespace kendo.ui { imageUrl?: string; menuButtons?: ToolBarItemMenuButton[]; overflow?: string; - overflowTemplate?: string | Function; + overflowTemplate?: string|Function; primary?: boolean; selected?: boolean; showIcon?: string; showText?: string; spriteCssClass?: string; - template?: string | Function; + template?: string|Function; text?: string; togglable?: boolean; toggle?: Function; @@ -7289,7 +7288,7 @@ declare namespace kendo.ui { interface TooltipOptions { name?: string; autoHide?: boolean; - animation?: boolean | TooltipAnimation; + animation?: boolean|TooltipAnimation; content?: TooltipContent; callout?: boolean; filter?: string; @@ -7514,7 +7513,7 @@ declare namespace kendo.ui { } interface TreeListColumnFilterable { - ui?: string | Function; + ui?: string|Function; } interface TreeListColumnSortable { @@ -7527,16 +7526,16 @@ declare namespace kendo.ui { encoded?: boolean; expandable?: boolean; field?: string; - filterable?: boolean | TreeListColumnFilterable; - footerTemplate?: string | Function; + filterable?: boolean|TreeListColumnFilterable; + footerTemplate?: string|Function; format?: string; headerAttributes?: any; - headerTemplate?: string | Function; + headerTemplate?: string|Function; minScreenWidth?: number; - sortable?: boolean | TreeListColumnSortable; - template?: string | Function; + sortable?: boolean|TreeListColumnSortable; + template?: string|Function; title?: string; - width?: string | number; + width?: string|number; hidden?: boolean; menu?: boolean; locked?: boolean; @@ -7546,7 +7545,7 @@ declare namespace kendo.ui { interface TreeListEditable { mode?: string; move?: boolean; - template?: string | Function; + template?: string|Function; window?: any; } @@ -7595,15 +7594,15 @@ declare namespace kendo.ui { } interface TreeListPdfMargin { - bottom?: number | string; - left?: number | string; - right?: number | string; - top?: number | string; + bottom?: number|string; + left?: number|string; + right?: number|string; + top?: number|string; } interface TreeListPdf { author?: string; - avoidLinks?: boolean | string; + avoidLinks?: boolean|string; creator?: string; date?: Date; fileName?: string; @@ -7611,7 +7610,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: TreeListPdfMargin; - paperSize?: string | any; + paperSize?: string|any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -7634,17 +7633,17 @@ declare namespace kendo.ui { columns?: TreeListColumn[]; resizable?: boolean; reorderable?: boolean; - columnMenu?: boolean | TreeListColumnMenu; - dataSource?: any | any | kendo.data.TreeListDataSource; - editable?: boolean | TreeListEditable; + columnMenu?: boolean|TreeListColumnMenu; + dataSource?: any|any|kendo.data.TreeListDataSource; + editable?: boolean|TreeListEditable; excel?: TreeListExcel; - filterable?: boolean | TreeListFilterable; - height?: number | string; + filterable?: boolean|TreeListFilterable; + height?: number|string; messages?: TreeListMessages; pdf?: TreeListPdf; - scrollable?: boolean | any; - selectable?: boolean | string; - sortable?: boolean | TreeListSortable; + scrollable?: boolean|any; + selectable?: boolean|string; + sortable?: boolean|TreeListSortable; toolbar?: TreeListToolbarItem[]; cancel?(e: TreeListCancelEvent): void; change?(e: TreeListChangeEvent): void; @@ -7859,14 +7858,14 @@ declare namespace kendo.ui { } interface TreeViewAnimation { - collapse?: boolean | TreeViewAnimationCollapse; - expand?: boolean | TreeViewAnimationExpand; + collapse?: boolean|TreeViewAnimationCollapse; + expand?: boolean|TreeViewAnimationExpand; } interface TreeViewCheckboxes { checkChildren?: boolean; name?: string; - template?: string | Function; + template?: string|Function; } interface TreeViewMessages { @@ -7877,19 +7876,19 @@ declare namespace kendo.ui { interface TreeViewOptions { name?: string; - animation?: boolean | TreeViewAnimation; + animation?: boolean|TreeViewAnimation; autoBind?: boolean; autoScroll?: boolean; - checkboxes?: boolean | TreeViewCheckboxes; + checkboxes?: boolean|TreeViewCheckboxes; dataImageUrlField?: string; - dataSource?: any | any | kendo.data.HierarchicalDataSource; + dataSource?: any|any|kendo.data.HierarchicalDataSource; dataSpriteCssClassField?: string; - dataTextField?: string | any; + dataTextField?: string|any; dataUrlField?: string; dragAndDrop?: boolean; loadOnDemand?: boolean; messages?: TreeViewMessages; - template?: string | Function; + template?: string|Function; change?(e: TreeViewEvent): void; check?(e: TreeViewCheckEvent): void; collapse?(e: TreeViewCollapseEvent): void; @@ -8022,7 +8021,7 @@ declare namespace kendo.ui { localization?: UploadLocalization; multiple?: boolean; showFileList?: boolean; - template?: string | Function; + template?: string|Function; cancel?(e: UploadCancelEvent): void; complete?(e: UploadEvent): void; error?(e: UploadErrorEvent): void; @@ -8176,8 +8175,8 @@ declare namespace kendo.ui { } interface WindowPosition { - top?: number | string; - left?: number | string; + top?: number|string; + left?: number|string; } interface WindowRefreshOptions { @@ -8192,13 +8191,13 @@ declare namespace kendo.ui { interface WindowOptions { name?: string; actions?: any; - animation?: boolean | WindowAnimation; - appendTo?: any | string; + animation?: boolean|WindowAnimation; + appendTo?: any|string; autoFocus?: boolean; content?: WindowContent; draggable?: boolean; iframe?: boolean; - height?: number | string; + height?: number|string; maxHeight?: number; maxWidth?: number; minHeight?: number; @@ -8208,9 +8207,9 @@ declare namespace kendo.ui { position?: WindowPosition; resizable?: boolean; scrollable?: boolean; - title?: string | boolean; + title?: string|boolean; visible?: boolean; - width?: number | string; + width?: number|string; activate?(e: WindowEvent): void; close?(e: WindowCloseEvent): void; deactivate?(e: WindowEvent): void; @@ -8380,7 +8379,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartAxisDefaultsCrosshairTooltipPadding; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -8408,7 +8407,7 @@ declare namespace kendo.dataviz.ui { interface ChartAxisDefaultsLabelsRotation { align?: string; - angle?: number | string; + angle?: number|string; } interface ChartAxisDefaultsLabels { @@ -8420,7 +8419,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartAxisDefaultsLabelsRotation; skip?: number; step?: number; - template?: string | Function; + template?: string|Function; visible?: boolean; visual?: Function; } @@ -8558,7 +8557,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartCategoryAxisItemCrosshairTooltipPadding; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -8600,7 +8599,7 @@ declare namespace kendo.dataviz.ui { interface ChartCategoryAxisItemLabelsRotation { align?: string; - angle?: number | string; + angle?: number|string; } interface ChartCategoryAxisItemLabels { @@ -8617,7 +8616,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartCategoryAxisItemLabelsRotation; skip?: number; step?: number; - template?: string | Function; + template?: string|Function; visible?: boolean; visual?: Function; } @@ -8689,7 +8688,7 @@ declare namespace kendo.dataviz.ui { border?: ChartCategoryAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -8735,7 +8734,7 @@ declare namespace kendo.dataviz.ui { border?: ChartCategoryAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -8813,7 +8812,7 @@ declare namespace kendo.dataviz.ui { interface ChartCategoryAxisItem { autoBaseUnitSteps?: ChartCategoryAxisItemAutoBaseUnitSteps; - axisCrossingValue?: any | Date | any; + axisCrossingValue?: any|Date|any; background?: string; baseUnit?: string; baseUnitStep?: any; @@ -8877,7 +8876,7 @@ declare namespace kendo.dataviz.ui { interface ChartLegendInactiveItemsLabels { color?: string; font?: string; - template?: string | Function; + template?: string|Function; } interface ChartLegendInactiveItems { @@ -8908,7 +8907,7 @@ declare namespace kendo.dataviz.ui { font?: string; margin?: ChartLegendLabelsMargin; padding?: ChartLegendLabelsPadding; - template?: string | Function; + template?: string|Function; } interface ChartLegendMargin { @@ -9006,10 +9005,10 @@ declare namespace kendo.dataviz.ui { } interface ChartPdfMargin { - bottom?: number | string; - left?: number | string; - right?: number | string; - top?: number | string; + bottom?: number|string; + left?: number|string; + right?: number|string; + top?: number|string; } interface ChartPdf { @@ -9021,7 +9020,7 @@ declare namespace kendo.dataviz.ui { keywords?: string; landscape?: boolean; margin?: ChartPdfMargin; - paperSize?: string | any; + paperSize?: string|any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -9057,10 +9056,10 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemBorder { - color?: string | Function; - dashType?: string | Function; - opacity?: number | Function; - width?: number | Function; + color?: string|Function; + dashType?: string|Function; + opacity?: number|Function; + width?: number|Function; } interface ChartSeriesItemConnectors { @@ -9075,26 +9074,26 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemErrorBars { - value?: string | number | any | Function; + value?: string|number|any|Function; visual?: Function; - xValue?: string | number | any | Function; - yValue?: string | number | any | Function; + xValue?: string|number|any|Function; + yValue?: string|number|any|Function; endCaps?: boolean; color?: string; line?: ChartSeriesItemErrorBarsLine; } interface ChartSeriesItemExtremesBorder { - color?: string | Function; - width?: number | Function; + color?: string|Function; + width?: number|Function; } interface ChartSeriesItemExtremes { - background?: string | Function; + background?: string|Function; border?: ChartSeriesItemExtremesBorder; - size?: number | Function; - type?: string | Function; - rotation?: number | Function; + size?: number|Function; + type?: string|Function; + rotation?: number|Function; } interface ChartSeriesItemHighlightBorder { @@ -9120,15 +9119,15 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemLabelsBorder { - color?: string | Function; - dashType?: string | Function; - width?: number | Function; + color?: string|Function; + dashType?: string|Function; + width?: number|Function; } interface ChartSeriesItemLabelsFromBorder { - color?: string | Function; - dashType?: string | Function; - width?: number | Function; + color?: string|Function; + dashType?: string|Function; + width?: number|Function; } interface ChartSeriesItemLabelsFromMargin { @@ -9146,16 +9145,16 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemLabelsFrom { - background?: string | Function; + background?: string|Function; border?: ChartSeriesItemLabelsFromBorder; - color?: string | Function; - font?: string | Function; - format?: string | Function; + color?: string|Function; + font?: string|Function; + format?: string|Function; margin?: ChartSeriesItemLabelsFromMargin; padding?: ChartSeriesItemLabelsFromPadding; - position?: string | Function; - template?: string | Function; - visible?: boolean | Function; + position?: string|Function; + template?: string|Function; + visible?: boolean|Function; } interface ChartSeriesItemLabelsMargin { @@ -9173,9 +9172,9 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemLabelsToBorder { - color?: string | Function; - dashType?: string | Function; - width?: number | Function; + color?: string|Function; + dashType?: string|Function; + width?: number|Function; } interface ChartSeriesItemLabelsToMargin { @@ -9193,31 +9192,31 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemLabelsTo { - background?: string | Function; + background?: string|Function; border?: ChartSeriesItemLabelsToBorder; - color?: string | Function; - font?: string | Function; - format?: string | Function; + color?: string|Function; + font?: string|Function; + format?: string|Function; margin?: ChartSeriesItemLabelsToMargin; padding?: ChartSeriesItemLabelsToPadding; - position?: string | Function; - template?: string | Function; - visible?: boolean | Function; + position?: string|Function; + template?: string|Function; + visible?: boolean|Function; } interface ChartSeriesItemLabels { align?: string; - background?: string | Function; + background?: string|Function; border?: ChartSeriesItemLabelsBorder; - color?: string | Function; + color?: string|Function; distance?: number; - font?: string | Function; - format?: string | Function; + font?: string|Function; + format?: string|Function; margin?: ChartSeriesItemLabelsMargin; padding?: ChartSeriesItemLabelsPadding; - position?: string | Function; - template?: string | Function; - visible?: boolean | Function; + position?: string|Function; + template?: string|Function; + visible?: boolean|Function; visual?: Function; from?: ChartSeriesItemLabelsFrom; to?: ChartSeriesItemLabelsTo; @@ -9238,18 +9237,18 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemMarkersBorder { - color?: string | Function; - width?: number | Function; + color?: string|Function; + width?: number|Function; } interface ChartSeriesItemMarkers { - background?: string | Function; + background?: string|Function; border?: ChartSeriesItemMarkersBorder; - size?: number | Function; - type?: string | Function; - visible?: boolean | Function; + size?: number|Function; + type?: string|Function; + visible?: boolean|Function; visual?: Function; - rotation?: number | Function; + rotation?: number|Function; } interface ChartSeriesItemNegativeValues { @@ -9281,7 +9280,7 @@ declare namespace kendo.dataviz.ui { border?: ChartSeriesItemNotesLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -9303,16 +9302,16 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemOutliersBorder { - color?: string | Function; - width?: number | Function; + color?: string|Function; + width?: number|Function; } interface ChartSeriesItemOutliers { - background?: string | Function; + background?: string|Function; border?: ChartSeriesItemOutliersBorder; - size?: number | Function; - type?: string | Function; - rotation?: number | Function; + size?: number|Function; + type?: string|Function; + rotation?: number|Function; } interface ChartSeriesItemOverlay { @@ -9325,18 +9324,18 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemTargetBorder { - color?: string | Function; - dashType?: string | Function; - width?: number | Function; + color?: string|Function; + dashType?: string|Function; + width?: number|Function; } interface ChartSeriesItemTargetLine { - width?: any | Function; + width?: any|Function; } interface ChartSeriesItemTarget { border?: ChartSeriesItemTargetBorder; - color?: string | Function; + color?: string|Function; line?: ChartSeriesItemTargetLine; } @@ -9359,23 +9358,23 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartSeriesItemTooltipPadding; - template?: string | Function; + template?: string|Function; visible?: boolean; } interface ChartSeriesItem { - aggregate?: string | Function; + aggregate?: string|Function; axis?: string; border?: ChartSeriesItemBorder; categoryField?: string; closeField?: string; - color?: string | Function; + color?: string|Function; colorField?: string; connectors?: ChartSeriesItemConnectors; currentField?: string; dashType?: string; data?: any; - downColor?: string | Function; + downColor?: string|Function; downColorField?: string; segmentSpacing?: number; summaryField?: string; @@ -9426,7 +9425,7 @@ declare namespace kendo.dataviz.ui { size?: number; sizeField?: string; spacing?: number; - stack?: boolean | ChartSeriesItemStack; + stack?: boolean|ChartSeriesItemStack; startAngle?: number; target?: ChartSeriesItemTarget; targetField?: string; @@ -9485,7 +9484,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: ChartSeriesDefaultsLabelsFromMargin; padding?: ChartSeriesDefaultsLabelsFromPadding; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -9531,7 +9530,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: ChartSeriesDefaultsLabelsToMargin; padding?: ChartSeriesDefaultsLabelsToPadding; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -9543,7 +9542,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: ChartSeriesDefaultsLabelsMargin; padding?: ChartSeriesDefaultsLabelsPadding; - template?: string | Function; + template?: string|Function; visible?: boolean; visual?: Function; from?: ChartSeriesDefaultsLabelsFrom; @@ -9574,7 +9573,7 @@ declare namespace kendo.dataviz.ui { border?: ChartSeriesDefaultsNotesLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -9621,7 +9620,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartSeriesDefaultsTooltipPadding; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -9642,7 +9641,7 @@ declare namespace kendo.dataviz.ui { scatter?: any; scatterLine?: any; spacing?: number; - stack?: boolean | ChartSeriesDefaultsStack; + stack?: boolean|ChartSeriesDefaultsStack; type?: string; tooltip?: ChartSeriesDefaultsTooltip; verticalArea?: any; @@ -9705,8 +9704,8 @@ declare namespace kendo.dataviz.ui { opacity?: number; padding?: ChartTooltipPadding; shared?: boolean; - sharedTemplate?: string | Function; - template?: string | Function; + sharedTemplate?: string|Function; + template?: string|Function; visible?: boolean; } @@ -9730,7 +9729,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartValueAxisItemCrosshairTooltipPadding; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -9764,7 +9763,7 @@ declare namespace kendo.dataviz.ui { interface ChartValueAxisItemLabelsRotation { align?: string; - angle?: number | string; + angle?: number|string; } interface ChartValueAxisItemLabels { @@ -9779,7 +9778,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartValueAxisItemLabelsRotation; skip?: number; step?: number; - template?: string | Function; + template?: string|Function; visible?: boolean; visual?: Function; } @@ -9852,7 +9851,7 @@ declare namespace kendo.dataviz.ui { border?: ChartValueAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -9898,7 +9897,7 @@ declare namespace kendo.dataviz.ui { border?: ChartValueAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -9962,7 +9961,7 @@ declare namespace kendo.dataviz.ui { } interface ChartValueAxisItem { - axisCrossingValue?: any | Date | any; + axisCrossingValue?: any|Date|any; background?: string; color?: string; crosshair?: ChartValueAxisItemCrosshair; @@ -10007,7 +10006,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartXAxisItemCrosshairTooltipPadding; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -10049,7 +10048,7 @@ declare namespace kendo.dataviz.ui { interface ChartXAxisItemLabelsRotation { align?: string; - angle?: number | string; + angle?: number|string; } interface ChartXAxisItemLabels { @@ -10066,7 +10065,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartXAxisItemLabelsRotation; skip?: number; step?: number; - template?: string | Function; + template?: string|Function; visible?: boolean; visual?: Function; } @@ -10138,7 +10137,7 @@ declare namespace kendo.dataviz.ui { border?: ChartXAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -10184,7 +10183,7 @@ declare namespace kendo.dataviz.ui { border?: ChartXAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -10248,7 +10247,7 @@ declare namespace kendo.dataviz.ui { } interface ChartXAxisItem { - axisCrossingValue?: any | Date | any; + axisCrossingValue?: any|Date|any; background?: string; baseUnit?: string; color?: string; @@ -10295,7 +10294,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartYAxisItemCrosshairTooltipPadding; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -10354,7 +10353,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartYAxisItemLabelsRotation; skip?: number; step?: number; - template?: string | Function; + template?: string|Function; visible?: boolean; visual?: Function; } @@ -10426,7 +10425,7 @@ declare namespace kendo.dataviz.ui { border?: ChartYAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -10472,7 +10471,7 @@ declare namespace kendo.dataviz.ui { border?: ChartYAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -10536,7 +10535,7 @@ declare namespace kendo.dataviz.ui { } interface ChartYAxisItem { - axisCrossingValue?: any | Date | any; + axisCrossingValue?: any|Date|any; background?: string; baseUnit?: string; color?: string; @@ -10572,8 +10571,8 @@ declare namespace kendo.dataviz.ui { } interface ChartZoomable { - mousewheel?: boolean | ChartZoomableMousewheel; - selection?: boolean | ChartZoomableSelection; + mousewheel?: boolean|ChartZoomableMousewheel; + selection?: boolean|ChartZoomableSelection; } interface ChartExportImageOptions { @@ -10606,13 +10605,14 @@ declare namespace kendo.dataviz.ui { interface ChartOptions { name?: string; autoBind?: boolean; - axisDefaults?: any; + axisDefaults?: ChartAxisDefaults; categoryAxis?: ChartCategoryAxisItem[]; valueAxis?: ChartValueAxisItem[]; chartArea?: ChartChartArea; - dataSource?: any; + dataSource?: any|any|kendo.data.DataSource; legend?: ChartLegend; panes?: ChartPane[]; + pannable?: boolean|ChartPannable; pdf?: ChartPdf; plotArea?: ChartPlotArea; renderAs?: string; @@ -10625,6 +10625,7 @@ declare namespace kendo.dataviz.ui { transitions?: boolean; xAxis?: ChartXAxisItem[]; yAxis?: ChartYAxisItem[]; + zoomable?: boolean|ChartZoomable; axisLabelClick?(e: ChartAxisLabelClickEvent): void; legendItemClick?(e: ChartLegendItemClickEvent): void; legendItemHover?(e: ChartLegendItemHoverEvent): void; @@ -10635,14 +10636,13 @@ declare namespace kendo.dataviz.ui { noteClick?(e: ChartNoteClickEvent): void; noteHover?(e: ChartNoteHoverEvent): void; plotAreaClick?(e: ChartPlotAreaClickEvent): void; - pannable?:any; + plotAreaHover?(e: ChartPlotAreaHoverEvent): void; render?(e: ChartEvent): void; select?(e: ChartSelectEvent): void; selectEnd?(e: ChartSelectEndEvent): void; selectStart?(e: ChartSelectStartEvent): void; seriesClick?(e: ChartSeriesClickEvent): void; seriesHover?(e: ChartSeriesHoverEvent): void; - zoomable?:any; zoom?(e: ChartZoomEvent): void; zoomEnd?(e: ChartZoomEndEvent): void; zoomStart?(e: ChartZoomStartEvent): void; @@ -10875,7 +10875,7 @@ declare namespace kendo.dataviz.ui { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string | Function; + template?: string|Function; text?: string; visual?: Function; } @@ -10956,7 +10956,7 @@ declare namespace kendo.dataviz.ui { interface DiagramConnectionDefaults { content?: DiagramConnectionDefaultsContent; - editable?: boolean | DiagramConnectionDefaultsEditable; + editable?: boolean|DiagramConnectionDefaultsEditable; endCap?: DiagramConnectionDefaultsEndCap; fromConnector?: string; hover?: DiagramConnectionDefaultsHover; @@ -10974,7 +10974,7 @@ declare namespace kendo.dataviz.ui { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string | Function; + template?: string|Function; text?: string; visual?: Function; } @@ -11068,7 +11068,7 @@ declare namespace kendo.dataviz.ui { interface DiagramConnection { content?: DiagramConnectionContent; - editable?: boolean | DiagramConnectionEditable; + editable?: boolean|DiagramConnectionEditable; endCap?: DiagramConnectionEndCap; from?: DiagramConnectionFrom; fromConnector?: string; @@ -11087,7 +11087,7 @@ declare namespace kendo.dataviz.ui { } interface DiagramEditableDrag { - snap?: boolean | DiagramEditableDragSnap; + snap?: boolean|DiagramEditableDragSnap; } interface DiagramEditableResizeHandlesFill { @@ -11150,12 +11150,12 @@ declare namespace kendo.dataviz.ui { } interface DiagramEditable { - connectionTemplate?: string | Function; - drag?: boolean | DiagramEditableDrag; + connectionTemplate?: string|Function; + drag?: boolean|DiagramEditableDrag; remove?: boolean; - resize?: boolean | DiagramEditableResize; - rotate?: boolean | DiagramEditableRotate; - shapeTemplate?: string | Function; + resize?: boolean|DiagramEditableResize; + rotate?: boolean|DiagramEditableRotate; + shapeTemplate?: string|Function; tools?: DiagramEditableTool[]; } @@ -11191,10 +11191,10 @@ declare namespace kendo.dataviz.ui { } interface DiagramPdfMargin { - bottom?: number | string; - left?: number | string; - right?: number | string; - top?: number | string; + bottom?: number|string; + left?: number|string; + right?: number|string; + top?: number|string; } interface DiagramPdf { @@ -11206,7 +11206,7 @@ declare namespace kendo.dataviz.ui { keywords?: string; landscape?: boolean; margin?: DiagramPdfMargin; - paperSize?: string | any; + paperSize?: string|any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -11303,7 +11303,7 @@ declare namespace kendo.dataviz.ui { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string | Function; + template?: string|Function; text?: string; } @@ -11363,7 +11363,7 @@ declare namespace kendo.dataviz.ui { connectors?: DiagramShapeDefaultsConnector[]; connectorDefaults?: DiagramShapeDefaultsConnectorDefaults; content?: DiagramShapeDefaultsContent; - editable?: boolean | DiagramShapeDefaultsEditable; + editable?: boolean|DiagramShapeDefaultsEditable; fill?: DiagramShapeDefaultsFill; height?: number; hover?: DiagramShapeDefaultsHover; @@ -11461,7 +11461,7 @@ declare namespace kendo.dataviz.ui { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string | Function; + template?: string|Function; text?: string; } @@ -11519,7 +11519,7 @@ declare namespace kendo.dataviz.ui { connectors?: DiagramShapeConnector[]; connectorDefaults?: DiagramShapeConnectorDefaults; content?: DiagramShapeContent; - editable?: boolean | DiagramShapeEditable; + editable?: boolean|DiagramShapeEditable; fill?: DiagramShapeFill; height?: number; hover?: DiagramShapeHover; @@ -11556,16 +11556,16 @@ declare namespace kendo.dataviz.ui { autoBind?: boolean; connectionDefaults?: DiagramConnectionDefaults; connections?: DiagramConnection[]; - connectionsDataSource?: any | any | kendo.data.DataSource; - dataSource?: any | any | kendo.data.DataSource; - editable?: boolean | DiagramEditable; + connectionsDataSource?: any|any|kendo.data.DataSource; + dataSource?: any|any|kendo.data.DataSource; + editable?: boolean|DiagramEditable; layout?: DiagramLayout; - pannable?: boolean | DiagramPannable; + pannable?: boolean|DiagramPannable; pdf?: DiagramPdf; - selectable?: boolean | DiagramSelectable; + selectable?: boolean|DiagramSelectable; shapeDefaults?: DiagramShapeDefaults; shapes?: DiagramShape[]; - template?: string | Function; + template?: string|Function; zoom?: number; zoomMax?: number; zoomMin?: number; @@ -11773,7 +11773,7 @@ declare namespace kendo.dataviz.ui { interface LinearGaugePointerItem { border?: LinearGaugePointerItemBorder; color?: string; - margin?: number | any; + margin?: number|any; opacity?: number; shape?: string; size?: number; @@ -11809,7 +11809,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: LinearGaugeScaleLabelsMargin; padding?: LinearGaugeScaleLabelsPadding; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -11941,9 +11941,9 @@ declare namespace kendo.dataviz.ui { } interface MapControls { - attribution?: boolean | MapControlsAttribution; - navigator?: boolean | MapControlsNavigator; - zoom?: boolean | MapControlsZoom; + attribution?: boolean|MapControlsAttribution; + navigator?: boolean|MapControlsNavigator; + zoom?: boolean|MapControlsZoom; } interface MapLayerDefaultsBing { @@ -11977,7 +11977,7 @@ declare namespace kendo.dataviz.ui { maxSize?: number; minSize?: number; style?: MapLayerDefaultsBubbleStyle; - symbol?: string | Function; + symbol?: string|Function; } interface MapLayerDefaultsMarkerTooltipAnimationClose { @@ -12111,8 +12111,8 @@ declare namespace kendo.dataviz.ui { interface MapLayer { attribution?: string; autoBind?: boolean; - dataSource?: any | any | kendo.data.DataSource; - extent?: any | kendo.dataviz.map.Extent; + dataSource?: any|any|kendo.data.DataSource; + extent?: any|kendo.dataviz.map.Extent; key?: string; imagerySet?: string; culture?: string; @@ -12125,7 +12125,7 @@ declare namespace kendo.dataviz.ui { minSize?: number; opacity?: number; subdomains?: any; - symbol?: string | Function; + symbol?: string|Function; type?: string; style?: MapLayerStyle; urlTemplate?: string; @@ -12205,7 +12205,7 @@ declare namespace kendo.dataviz.ui { } interface MapMarker { - location?: any | kendo.dataviz.map.Location; + location?: any|kendo.dataviz.map.Location; shape?: string; title?: string; tooltip?: MapMarkerTooltip; @@ -12213,7 +12213,7 @@ declare namespace kendo.dataviz.ui { interface MapOptions { name?: string; - center?: any | kendo.dataviz.map.Location; + center?: any|kendo.dataviz.map.Location; controls?: MapControls; layerDefaults?: MapLayerDefaults; layers?: MapLayer[]; @@ -12378,8 +12378,8 @@ declare namespace kendo.dataviz.ui { errorCorrection?: string; padding?: number; renderAs?: string; - size?: number | string; - value?: number | string; + size?: number|string; + value?: number|string; } interface QRCodeEvent { sender: QRCode; @@ -12479,7 +12479,7 @@ declare namespace kendo.dataviz.ui { margin?: RadialGaugeScaleLabelsMargin; padding?: RadialGaugeScaleLabelsPadding; position?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -12584,8 +12584,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number | any; - template?: string | Function; + padding?: number|any; + template?: string|Function; visible?: boolean; } @@ -12610,13 +12610,13 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number | any; + margin?: number|any; mirror?: boolean; - padding?: number | any; + padding?: number|any; rotation?: number; skip?: number; step?: number; - template?: string | Function; + template?: string|Function; visible?: boolean; culture?: string; dateFormats?: any; @@ -12689,7 +12689,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineCategoryAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -12735,7 +12735,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineCategoryAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -12774,7 +12774,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineCategoryAxisItemTitleBorder; color?: string; font?: string; - margin?: number | any; + margin?: number|any; position?: string; rotation?: number; text?: string; @@ -12782,7 +12782,7 @@ declare namespace kendo.dataviz.ui { } interface SparklineCategoryAxisItem { - axisCrossingValue?: any | Date | any; + axisCrossingValue?: any|Date|any; categories?: any; color?: string; field?: string; @@ -12822,7 +12822,7 @@ declare namespace kendo.dataviz.ui { opacity?: number; border?: SparklineChartAreaBorder; height?: number; - margin?: number | any; + margin?: number|any; width?: number; } @@ -12836,14 +12836,14 @@ declare namespace kendo.dataviz.ui { background?: string; opacity?: number; border?: SparklinePlotAreaBorder; - margin?: number | any; + margin?: number|any; } interface SparklineSeriesItemBorder { - color?: string | Function; - dashType?: string | Function; - opacity?: number | Function; - width?: number | Function; + color?: string|Function; + dashType?: string|Function; + opacity?: number|Function; + width?: number|Function; } interface SparklineSeriesItemConnectors { @@ -12866,24 +12866,24 @@ declare namespace kendo.dataviz.ui { } interface SparklineSeriesItemLabelsBorder { - color?: string | Function; - dashType?: string | Function; - width?: number | Function; + color?: string|Function; + dashType?: string|Function; + width?: number|Function; } interface SparklineSeriesItemLabels { align?: string; - background?: string | Function; + background?: string|Function; border?: SparklineSeriesItemLabelsBorder; - color?: string | Function; + color?: string|Function; distance?: number; - font?: string | Function; - format?: string | Function; - margin?: number | any; - padding?: number | any; - position?: string | Function; - template?: string | Function; - visible?: boolean | Function; + font?: string|Function; + format?: string|Function; + margin?: number|any; + padding?: number|any; + position?: string|Function; + template?: string|Function; + visible?: boolean|Function; } interface SparklineSeriesItemLine { @@ -12894,17 +12894,17 @@ declare namespace kendo.dataviz.ui { } interface SparklineSeriesItemMarkersBorder { - color?: string | Function; - width?: number | Function; + color?: string|Function; + width?: number|Function; } interface SparklineSeriesItemMarkers { - background?: string | Function; + background?: string|Function; border?: SparklineSeriesItemMarkersBorder; - size?: number | Function; - type?: string | Function; - visible?: boolean | Function; - rotation?: number | Function; + size?: number|Function; + type?: string|Function; + visible?: boolean|Function; + rotation?: number|Function; } interface SparklineSeriesItemNotesIconBorder { @@ -12931,7 +12931,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineSeriesItemNotesLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -12961,18 +12961,18 @@ declare namespace kendo.dataviz.ui { } interface SparklineSeriesItemTargetBorder { - color?: string | Function; - dashType?: string | Function; + color?: string|Function; + dashType?: string|Function; width?: number; } interface SparklineSeriesItemTargetLine { - width?: any | Function; + width?: any|Function; } interface SparklineSeriesItemTarget { line?: SparklineSeriesItemTargetLine; - color?: string | Function; + color?: string|Function; border?: SparklineSeriesItemTargetBorder; } @@ -12987,8 +12987,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number | any; - template?: string | Function; + padding?: number|any; + template?: string|Function; visible?: boolean; } @@ -13002,11 +13002,11 @@ declare namespace kendo.dataviz.ui { field?: string; name?: string; highlight?: SparklineSeriesItemHighlight; - aggregate?: string | Function; + aggregate?: string|Function; axis?: string; border?: SparklineSeriesItemBorder; categoryField?: string; - color?: string | Function; + color?: string|Function; colorField?: string; connectors?: SparklineSeriesItemConnectors; gap?: number; @@ -13022,7 +13022,7 @@ declare namespace kendo.dataviz.ui { size?: number; startAngle?: number; spacing?: number; - stack?: boolean | SparklineSeriesItemStack; + stack?: boolean|SparklineSeriesItemStack; tooltip?: SparklineSeriesItemTooltip; width?: number; target?: SparklineSeriesItemTarget; @@ -13048,9 +13048,9 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number | any; - padding?: number | any; - template?: string | Function; + margin?: number|any; + padding?: number|any; + template?: string|Function; visible?: boolean; } @@ -13069,8 +13069,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number | any; - template?: string | Function; + padding?: number|any; + template?: string|Function; visible?: boolean; } @@ -13085,7 +13085,7 @@ declare namespace kendo.dataviz.ui { overlay?: any; pie?: any; spacing?: number; - stack?: boolean | SparklineSeriesDefaultsStack; + stack?: boolean|SparklineSeriesDefaultsStack; type?: string; tooltip?: SparklineSeriesDefaultsTooltip; } @@ -13101,8 +13101,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number | any; - template?: string | Function; + padding?: number|any; + template?: string|Function; visible?: boolean; shared?: boolean; sharedTemplate?: string; @@ -13119,8 +13119,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number | any; - template?: string | Function; + padding?: number|any; + template?: string|Function; visible?: boolean; } @@ -13145,13 +13145,13 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number | any; + margin?: number|any; mirror?: boolean; - padding?: number | any; + padding?: number|any; rotation?: number; skip?: number; step?: number; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -13221,7 +13221,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineValueAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -13267,7 +13267,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineValueAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -13306,8 +13306,8 @@ declare namespace kendo.dataviz.ui { border?: SparklineValueAxisItemTitleBorder; color?: string; font?: string; - margin?: number | any; - padding?: number | any; + margin?: number|any; + padding?: number|any; position?: string; rotation?: number; text?: string; @@ -13315,7 +13315,7 @@ declare namespace kendo.dataviz.ui { } interface SparklineValueAxisItem { - axisCrossingValue?: any | Date | any; + axisCrossingValue?: any|Date|any; color?: string; labels?: SparklineValueAxisItemLabels; line?: SparklineValueAxisItemLine; @@ -13511,8 +13511,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number | any; - template?: string | Function; + padding?: number|any; + template?: string|Function; visible?: boolean; } @@ -13537,13 +13537,13 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number | any; + margin?: number|any; mirror?: boolean; - padding?: number | any; + padding?: number|any; rotation?: number; skip?: number; step?: number; - template?: string | Function; + template?: string|Function; visible?: boolean; culture?: string; dateFormats?: any; @@ -13616,7 +13616,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartCategoryAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -13662,7 +13662,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartCategoryAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -13714,7 +13714,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartCategoryAxisItemTitleBorder; color?: string; font?: string; - margin?: number | any; + margin?: number|any; position?: string; rotation?: number; text?: string; @@ -13722,7 +13722,7 @@ declare namespace kendo.dataviz.ui { } interface StockChartCategoryAxisItem { - axisCrossingValue?: any | Date | any; + axisCrossingValue?: any|Date|any; categories?: any; color?: string; field?: string; @@ -13765,7 +13765,7 @@ declare namespace kendo.dataviz.ui { opacity?: number; border?: StockChartChartAreaBorder; height?: number; - margin?: number | any; + margin?: number|any; width?: number; } @@ -13806,10 +13806,10 @@ declare namespace kendo.dataviz.ui { border?: StockChartLegendBorder; item?: StockChartLegendItem; labels?: StockChartLegendLabels; - margin?: number | any; + margin?: number|any; offsetX?: number; offsetY?: number; - padding?: number | any; + padding?: number|any; position?: string; reverse?: boolean; visible?: boolean; @@ -13846,7 +13846,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: StockChartNavigatorCategoryAxisItemCrosshairTooltipPadding; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -13900,7 +13900,7 @@ declare namespace kendo.dataviz.ui { rotation?: number; skip?: number; step?: number; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -13971,7 +13971,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartNavigatorCategoryAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -14017,7 +14017,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartNavigatorCategoryAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -14080,7 +14080,7 @@ declare namespace kendo.dataviz.ui { interface StockChartNavigatorCategoryAxisItem { autoBaseUnitSteps?: StockChartNavigatorCategoryAxisItemAutoBaseUnitSteps; - axisCrossingValue?: any | Date | any; + axisCrossingValue?: any|Date|any; background?: string; baseUnit?: string; baseUnitStep?: any; @@ -14109,7 +14109,7 @@ declare namespace kendo.dataviz.ui { interface StockChartNavigatorHint { visible?: boolean; - template?: string | Function; + template?: string|Function; format?: string; } @@ -14210,10 +14210,10 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number | any; - padding?: number | any; + margin?: number|any; + padding?: number|any; position?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -14231,7 +14231,7 @@ declare namespace kendo.dataviz.ui { interface StockChartNavigatorSeriesItemMarkers { background?: string; border?: StockChartNavigatorSeriesItemMarkersBorder; - rotation?: number | Function; + rotation?: number|Function; size?: number; type?: string; visible?: boolean; @@ -14257,8 +14257,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number | any; - template?: string | Function; + padding?: number|any; + template?: string|Function; visible?: boolean; } @@ -14271,7 +14271,7 @@ declare namespace kendo.dataviz.ui { categoryField?: string; name?: string; highlight?: StockChartNavigatorSeriesItemHighlight; - aggregate?: string | Function; + aggregate?: string|Function; axis?: string; border?: StockChartNavigatorSeriesItemBorder; closeField?: string; @@ -14290,7 +14290,7 @@ declare namespace kendo.dataviz.ui { openField?: string; overlay?: StockChartNavigatorSeriesItemOverlay; spacing?: number; - stack?: boolean | StockChartNavigatorSeriesItemStack; + stack?: boolean|StockChartNavigatorSeriesItemStack; tooltip?: StockChartNavigatorSeriesItemTooltip; width?: number; } @@ -14324,7 +14324,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartPaneTitleBorder; color?: string; font?: string; - margin?: number | any; + margin?: number|any; position?: string; text?: string; visible?: boolean; @@ -14332,8 +14332,8 @@ declare namespace kendo.dataviz.ui { interface StockChartPane { name?: string; - margin?: number | any; - padding?: number | any; + margin?: number|any; + padding?: number|any; background?: string; border?: StockChartPaneBorder; clip?: boolean; @@ -14342,10 +14342,10 @@ declare namespace kendo.dataviz.ui { } interface StockChartPdfMargin { - bottom?: number | string; - left?: number | string; - right?: number | string; - top?: number | string; + bottom?: number|string; + left?: number|string; + right?: number|string; + top?: number|string; } interface StockChartPdf { @@ -14357,7 +14357,7 @@ declare namespace kendo.dataviz.ui { keywords?: string; landscape?: boolean; margin?: StockChartPdfMargin; - paperSize?: string | any; + paperSize?: string|any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -14374,14 +14374,14 @@ declare namespace kendo.dataviz.ui { background?: string; opacity?: number; border?: StockChartPlotAreaBorder; - margin?: number | any; + margin?: number|any; } interface StockChartSeriesItemBorder { - color?: string | Function; - dashType?: string | Function; - opacity?: number | Function; - width?: number | Function; + color?: string|Function; + dashType?: string|Function; + opacity?: number|Function; + width?: number|Function; } interface StockChartSeriesItemHighlightBorder { @@ -14405,22 +14405,22 @@ declare namespace kendo.dataviz.ui { } interface StockChartSeriesItemLabelsBorder { - color?: string | Function; - dashType?: string | Function; - width?: number | Function; + color?: string|Function; + dashType?: string|Function; + width?: number|Function; } interface StockChartSeriesItemLabels { - background?: string | Function; + background?: string|Function; border?: StockChartSeriesItemLabelsBorder; - color?: string | Function; - font?: string | Function; - format?: string | Function; - margin?: number | any; - padding?: number | any; - position?: string | Function; - template?: string | Function; - visible?: boolean | Function; + color?: string|Function; + font?: string|Function; + format?: string|Function; + margin?: number|any; + padding?: number|any; + position?: string|Function; + template?: string|Function; + visible?: boolean|Function; } interface StockChartSeriesItemLine { @@ -14431,17 +14431,17 @@ declare namespace kendo.dataviz.ui { } interface StockChartSeriesItemMarkersBorder { - color?: string | Function; - width?: number | Function; + color?: string|Function; + width?: number|Function; } interface StockChartSeriesItemMarkers { - background?: string | Function; + background?: string|Function; border?: StockChartSeriesItemMarkersBorder; - size?: number | Function; - rotation?: number | Function; - type?: string | Function; - visible?: boolean | Function; + size?: number|Function; + rotation?: number|Function; + type?: string|Function; + visible?: boolean|Function; } interface StockChartSeriesItemNotesIconBorder { @@ -14468,7 +14468,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartSeriesItemNotesLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -14498,18 +14498,18 @@ declare namespace kendo.dataviz.ui { } interface StockChartSeriesItemTargetBorder { - color?: string | Function; - dashType?: string | Function; - width?: number | Function; + color?: string|Function; + dashType?: string|Function; + width?: number|Function; } interface StockChartSeriesItemTargetLine { - width?: any | Function; + width?: any|Function; } interface StockChartSeriesItemTarget { line?: StockChartSeriesItemTargetLine; - color?: string | Function; + color?: string|Function; border?: StockChartSeriesItemTargetBorder; } @@ -14524,8 +14524,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number | any; - template?: string | Function; + padding?: number|any; + template?: string|Function; visible?: boolean; } @@ -14540,13 +14540,13 @@ declare namespace kendo.dataviz.ui { targetField?: string; name?: string; highlight?: StockChartSeriesItemHighlight; - aggregate?: string | Function; + aggregate?: string|Function; axis?: string; border?: StockChartSeriesItemBorder; closeField?: string; - color?: string | Function; + color?: string|Function; colorField?: string; - downColor?: string | Function; + downColor?: string|Function; downColorField?: string; gap?: number; labels?: StockChartSeriesItemLabels; @@ -14560,7 +14560,7 @@ declare namespace kendo.dataviz.ui { openField?: string; overlay?: StockChartSeriesItemOverlay; spacing?: number; - stack?: boolean | StockChartSeriesItemStack; + stack?: boolean|StockChartSeriesItemStack; tooltip?: StockChartSeriesItemTooltip; visibleInLegend?: boolean; width?: number; @@ -14587,9 +14587,9 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number | any; - padding?: number | any; - template?: string | Function; + margin?: number|any; + padding?: number|any; + template?: string|Function; visible?: boolean; } @@ -14608,8 +14608,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number | any; - template?: string | Function; + padding?: number|any; + template?: string|Function; visible?: boolean; } @@ -14625,7 +14625,7 @@ declare namespace kendo.dataviz.ui { overlay?: any; pie?: any; spacing?: number; - stack?: boolean | StockChartSeriesDefaultsStack; + stack?: boolean|StockChartSeriesDefaultsStack; type?: string; tooltip?: StockChartSeriesDefaultsTooltip; } @@ -14642,8 +14642,8 @@ declare namespace kendo.dataviz.ui { border?: StockChartTitleBorder; font?: string; color?: string; - margin?: number | any; - padding?: number | any; + margin?: number|any; + padding?: number|any; position?: string; text?: string; visible?: boolean; @@ -14660,8 +14660,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number | any; - template?: string | Function; + padding?: number|any; + template?: string|Function; visible?: boolean; shared?: boolean; sharedTemplate?: string; @@ -14678,8 +14678,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number | any; - template?: string | Function; + padding?: number|any; + template?: string|Function; visible?: boolean; } @@ -14704,13 +14704,13 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number | any; + margin?: number|any; mirror?: boolean; - padding?: number | any; + padding?: number|any; rotation?: number; skip?: number; step?: number; - template?: string | Function; + template?: string|Function; visible?: boolean; } @@ -14780,7 +14780,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartValueAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -14826,7 +14826,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartValueAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string | Function; + template?: string|Function; visible?: boolean; rotation?: number; format?: string; @@ -14865,8 +14865,8 @@ declare namespace kendo.dataviz.ui { border?: StockChartValueAxisItemTitleBorder; color?: string; font?: string; - margin?: number | any; - padding?: number | any; + margin?: number|any; + padding?: number|any; position?: string; rotation?: number; text?: string; @@ -14874,7 +14874,7 @@ declare namespace kendo.dataviz.ui { } interface StockChartValueAxisItem { - axisCrossingValue?: any | Date | any; + axisCrossingValue?: any|Date|any; background?: string; color?: string; labels?: StockChartValueAxisItemLabels; @@ -15115,14 +15115,14 @@ declare namespace kendo.dataviz.ui { interface TreeMapOptions { name?: string; - dataSource?: any | any | kendo.data.HierarchicalDataSource; + dataSource?: any|any|kendo.data.HierarchicalDataSource; autoBind?: boolean; type?: string; theme?: string; valueField?: string; colorField?: string; textField?: string; - template?: string | Function; + template?: string|Function; colors?: any; itemCreated?(e: TreeMapItemCreatedEvent): void; dataBound?(e: TreeMapDataBoundEvent): void; @@ -15134,7 +15134,7 @@ declare namespace kendo.dataviz.ui { } interface TreeMapItemCreatedEvent extends TreeMapEvent { - element?: JQuery | Element; + element?: JQuery|Element; } interface TreeMapDataBoundEvent extends TreeMapEvent { @@ -15179,7 +15179,7 @@ declare namespace kendo.dataviz.map { nw: kendo.dataviz.map.Location; se: kendo.dataviz.map.Location; - constructor(nw: kendo.dataviz.map.Location | any, se: kendo.dataviz.map.Location | any); + constructor(nw: kendo.dataviz.map.Location|any, se: kendo.dataviz.map.Location|any); static create(a: kendo.dataviz.map.Location, b?: kendo.dataviz.map.Location): kendo.dataviz.map.Extent; static create(a: kendo.dataviz.map.Location, b?: any): kendo.dataviz.map.Extent; @@ -15319,7 +15319,7 @@ declare namespace kendo.dataviz.map { interface MarkerOptions { name?: string; - location?: any | kendo.dataviz.map.Location; + location?: any|kendo.dataviz.map.Location; shape?: string; title?: string; tooltip?: MarkerTooltip; @@ -15547,7 +15547,7 @@ declare namespace kendo.dataviz.diagram { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string | Function; + template?: string|Function; text?: string; visual?: Function; } @@ -16244,7 +16244,7 @@ declare namespace kendo.dataviz.diagram { interface ShapeOptions { name?: string; id?: string; - editable?: boolean | ShapeEditable; + editable?: boolean|ShapeEditable; path?: string; stroke?: ShapeStroke; type?: string; @@ -16344,10 +16344,10 @@ declare namespace kendo { namespace drawing { function align(elements: any, rect: kendo.geometry.Rect, alignment: string): void; - function drawDOM(element: JQuery, options?: any): JQueryPromise; - function exportImage(group: kendo.drawing.Group, options?: any): JQueryPromise; - function exportPDF(group: kendo.drawing.Group, options?: kendo.drawing.PDFOptions): JQueryPromise; - function exportSVG(group: kendo.drawing.Group, options?: any): JQueryPromise; + function drawDOM(element: JQuery, options: any): JQueryPromise; + function exportImage(group: kendo.drawing.Group, options: any): JQueryPromise; + function exportPDF(group: kendo.drawing.Group, options: kendo.drawing.PDFOptions): JQueryPromise; + function exportSVG(group: kendo.drawing.Group, options: any): JQueryPromise; function fit(element: kendo.drawing.Element, rect: kendo.geometry.Rect): void; function stack(elements: any): void; function vAlign(elements: any, rect: kendo.geometry.Rect, alignment: string): void; @@ -16363,40 +16363,40 @@ declare namespace kendo { function transformOrigin(firstElement: HTMLElement, secondElement: HTMLElement): any; } - function antiForgeryTokens(): any; - function bind(element: string, viewModel: any, namespace?: any): void; - function bind(element: string, viewModel: kendo.data.ObservableObject, namespace?: any): void; - function bind(element: JQuery, viewModel: any, namespace?: any): void; - function bind(element: JQuery, viewModel: kendo.data.ObservableObject, namespace?: any): void; - function bind(element: Element, viewModel: any, namespace?: any): void; - function bind(element: Element, viewModel: kendo.data.ObservableObject, namespace?: any): void; - function observableHierarchy(array: any): void; - function culture(culture: string): void; - function destroy(element: string): void; - function destroy(element: JQuery): void; - function destroy(element: Element): void; - function htmlEncode(value: string): string; - function parseDate(value: string, formats?: string, culture?: string): Date; - function parseDate(value: string, formats?: any, culture?: string): Date; - function parseFloat(value: string, culture?: string): number; - function parseInt(value: string, culture?: string): number; - function parseColor(color: string, noerror: boolean): kendo.Color; - function proxyModelSetters(): void; - function proxyModelSetters(data: kendo.data.Model): void; - function resize(element: string, force: boolean): void; - function resize(element: JQuery, force: boolean): void; - function resize(element: Element, force: boolean): void; - function saveAs(options: any): void; - function stringify(value: any): string; - function throttle(fn: Function, timeout: number): void; - function touchScroller(element: string): void; - function touchScroller(element: JQuery): void; - function touchScroller(element: Element): void; - function toString(value: Date, format: string, culture?: string): string; - function toString(value: number, format: string, culture?: string): string; - function unbind(element: string): void; - function unbind(element: JQuery): void; - function unbind(element: Element): void; + function antiForgeryTokens(): any; + function bind(element: string, viewModel: any, namespace?: any): void; + function bind(element: string, viewModel: kendo.data.ObservableObject, namespace?: any): void; + function bind(element: JQuery, viewModel: any, namespace?: any): void; + function bind(element: JQuery, viewModel: kendo.data.ObservableObject, namespace?: any): void; + function bind(element: Element, viewModel: any, namespace?: any): void; + function bind(element: Element, viewModel: kendo.data.ObservableObject, namespace?: any): void; + function observableHierarchy(array: any): void; + function culture(culture: string): void; + function destroy(element: string): void; + function destroy(element: JQuery): void; + function destroy(element: Element): void; + function htmlEncode(value: string): string; + function parseDate(value: string, formats?: string, culture?: string): Date; + function parseDate(value: string, formats?: any, culture?: string): Date; + function parseFloat(value: string, culture?: string): number; + function parseInt(value: string, culture?: string): number; + function parseColor(color: string, noerror: boolean): kendo.Color; + function proxyModelSetters(): void; + function proxyModelSetters(data: kendo.data.Model): void; + function resize(element: string, force: boolean): void; + function resize(element: JQuery, force: boolean): void; + function resize(element: Element, force: boolean): void; + function saveAs(options: any): void; + function stringify(value: any): string; + function throttle(fn: Function, timeout: number): void; + function touchScroller(element: string): void; + function touchScroller(element: JQuery): void; + function touchScroller(element: Element): void; + function toString(value: Date, format: string, culture?: string): string; + function toString(value: number, format: string, culture?: string): string; + function unbind(element: string): void; + function unbind(element: JQuery): void; + function unbind(element: Element): void; namespace pdf { function defineFont(map: any): void; @@ -16648,9 +16648,9 @@ declare namespace kendo.mobile.ui { } interface ActionSheetPopup { - direction?: number | string; - height?: number | string; - width?: number | string; + direction?: number|string; + height?: number|string; + width?: number|string; } interface ActionSheetOptions { @@ -17018,18 +17018,18 @@ declare namespace kendo.mobile.ui { name?: string; appendOnRefresh?: boolean; autoBind?: boolean; - dataSource?: kendo.data.DataSource | any; + dataSource?: kendo.data.DataSource|any; endlessScroll?: boolean; fixedHeaders?: boolean; - headerTemplate?: string | Function; + headerTemplate?: string|Function; loadMore?: boolean; messages?: ListViewMessages; pullToRefresh?: boolean; pullParameters?: Function; style?: string; - template?: string | Function; + template?: string|Function; type?: string; - filterable?: boolean | ListViewFilterable; + filterable?: boolean|ListViewFilterable; virtualViewSize?: number; click?(e: ListViewClickEvent): void; dataBound?(e: ListViewEvent): void; @@ -17241,8 +17241,8 @@ declare namespace kendo.mobile.ui { } interface PopOverPopup { - height?: number | string; - width?: number | string; + height?: number|string; + width?: number|string; } interface PopOverOptions { @@ -17298,8 +17298,8 @@ declare namespace kendo.mobile.ui { name?: string; autoBind?: boolean; bounceVelocityThreshold?: number; - contentHeight?: number | string; - dataSource?: kendo.data.DataSource | any; + contentHeight?: number|string; + dataSource?: kendo.data.DataSource|any; duration?: number; emptyTemplate?: string; enablePager?: boolean; @@ -17678,7 +17678,7 @@ declare namespace kendo.ooxml { wrap?: boolean; vAlign?: string; verticalAlign?: string; - value?: Date | number | string | boolean; + value?: Date|number|string|boolean; } interface WorkbookSheetRow { @@ -17884,7 +17884,7 @@ declare namespace kendo.dataviz.geometry { origin: kendo.geometry.Point; size: kendo.geometry.Size; - constructor(origin: kendo.geometry.Point | any, size: kendo.geometry.Size | any); + constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; @@ -18110,7 +18110,7 @@ declare namespace kendo.dataviz.drawing { } - interface FillOptions { + interface FillOptions { @@ -18409,7 +18409,7 @@ declare namespace kendo.dataviz.drawing { } - interface PDFOptions { + interface PDFOptions { @@ -18513,7 +18513,7 @@ declare namespace kendo.dataviz.drawing { interface RadialGradientOptions { name?: string; - center?: any | kendo.geometry.Point; + center?: any|kendo.geometry.Point; radius?: number; stops?: any; } @@ -18597,7 +18597,7 @@ declare namespace kendo.dataviz.drawing { } - interface StrokeOptions { + interface StrokeOptions { @@ -18651,8 +18651,8 @@ declare namespace kendo.dataviz.drawing { } interface SurfaceTooltip { - animation?: boolean | SurfaceTooltipAnimation; - appendTo?: string | JQuery; + animation?: boolean|SurfaceTooltipAnimation; + appendTo?: string|JQuery; } interface SurfaceOptions { @@ -18747,20 +18747,20 @@ declare namespace kendo.dataviz.drawing { } - interface TooltipOptions { + interface TooltipOptions { autoHide?: boolean; - content?: string | Function; + content?: string|Function; position?: string; - height?: number | string; + height?: number|string; hideDelay?: number; offset?: number; shared?: boolean; showAfter?: number; showOn?: string; - width?: number | string; + width?: number|string; From 41827bc8172dd4443e138a8d34e4ab90bfadd0e1 Mon Sep 17 00:00:00 2001 From: Gayan Ranasinghe Date: Mon, 25 Jul 2016 10:24:56 +0530 Subject: [PATCH 025/564] remove duplicates --- kendo-ui/kendo-ui.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index 941a432d81..ab09a8882f 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -2657,7 +2657,6 @@ declare namespace kendo.ui { separator?: string; suggest?: boolean; headerTemplate?: string|Function; - headerTemplate?: string | Function; template?: string | Function; valuePrimitive?: boolean; virtual?: boolean|AutoCompleteVirtual; From bc0ecd2c61698592e8754f7aeb7493f6b67c31f9 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Thu, 28 Jul 2016 11:08:36 +0900 Subject: [PATCH 026/564] 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 c80a0222639890181395715c21c3e2b6ba86347c Mon Sep 17 00:00:00 2001 From: Maxim Samoilov Date: Tue, 2 Aug 2016 20:25:07 +0700 Subject: [PATCH 027/564] Fix StatelessComponent interface Props always pass to StatelessComponent even if we pass no props. Example: ```js function Test(props) { return
props: {JSON.stringify(props)}
} React.render(, document.body) ``` will render into `props: {}` [jsfiddle](https://jsfiddle.net/LL25c28c/) We need to fix this because otherwise we have error: `Property 'propName' does not exist on type 'IntrinsicAttributes & (IMyInterface | undefined)'.` for that code: ```js const MyComponent: React.SFC = ({ propName }: IMyInterface) => { // ... } ``` --- react/react.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react/react.d.ts b/react/react.d.ts index da99fc737a..919b16d386 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -197,7 +197,7 @@ declare namespace __React { type SFC

= StatelessComponent

; interface StatelessComponent

{ - (props?: P, context?: any): ReactElement; + (props: P, context?: any): ReactElement; propTypes?: ValidationMap

; contextTypes?: ValidationMap; defaultProps?: P; From 0bb3ec00dd31d85a43695aca33b72ff69c444ee5 Mon Sep 17 00:00:00 2001 From: Diullei Date: Fri, 8 Jul 2016 00:44:30 -0300 Subject: [PATCH 028/564] 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 029/564] 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 030/564] 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 031/564] 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 032/564] 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 033/564] 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 034/564] 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 035/564] 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 036/564] 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 037/564] 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 cef1aab3400c1bec327573860d21e4b89622a593 Mon Sep 17 00:00:00 2001 From: linusbrolin Date: Tue, 9 Aug 2016 13:40:48 +0200 Subject: [PATCH 038/564] Typings for the mongoose-paginate plugin --- mongoose-paginate/mongoose-paginate.d.ts | 40 ++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 mongoose-paginate/mongoose-paginate.d.ts diff --git a/mongoose-paginate/mongoose-paginate.d.ts b/mongoose-paginate/mongoose-paginate.d.ts new file mode 100644 index 0000000000..48b0282bb4 --- /dev/null +++ b/mongoose-paginate/mongoose-paginate.d.ts @@ -0,0 +1,40 @@ +/// + +declare module 'mongoose' { + export interface PaginateOptions { + select?: Object | string; + sort?: Object | string; + populate?: Array | Array | Object | string; + lean?: boolean; + leanWithId?: boolean; + offset?: number; + page?: number; + limit?: number; + } + + export interface PaginateResult { + docs: Array; + total: number; + limit: number; + page?: number; + pages?: number; + offset?: number; + } + + export type PaginateModel = _PaginateModel & Model; + interface _PaginateModel { + paginate(query?: Object, options?: PaginateOptions, callback?: (err: any, result: PaginateResult) => void): Promise>; + } + + export function model( + name: string, + schema?: Schema, + collection?: string, + skipInit?: boolean): Statics & PaginateModel; +} + +declare module 'mongoose-paginate' { + import mongoose = require('mongoose'); + var _: (schema: mongoose.Schema) => void; + export = _; +} From ab34ec01c15dedbaec3de23400e73df593b4c043 Mon Sep 17 00:00:00 2001 From: linusbrolin Date: Tue, 9 Aug 2016 13:46:21 +0200 Subject: [PATCH 039/564] Typings for the passport-local-mongoose plugin --- .../passport-local-mongoose.d.ts | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 passport-local-mongoose/passport-local-mongoose.d.ts diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts new file mode 100644 index 0000000000..c0fd0bf6de --- /dev/null +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -0,0 +1,83 @@ +/// +/// + +declare module 'mongoose' { + import passportLocal = require('passport-local'); + + // methods + export interface PassportLocalDocument { + 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 { + 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; + register(user: PassportLocalModel, password: string, cb: (err: any) => void): void; + findByUsername(username: string, selectHashSaltFields: boolean, cb: (err: any) => void): any; + createStrategy(): passportLocal.Strategy; + } + + // error messages + export interface PassportLocalErrorMessages { + MissingPasswordError?: string; + AttemptTooSoonError?: string; + TooManyAttemptsError?: string; + NoSaltValueStoredError?: string; + IncorrectPasswordError?: string; + IncorrectUsernameError?: string; + MissingUsernameError?: string; + UserExistsError?: string; + } + + // plugin options + export interface PassportLocalOptions { + saltlen?: number; + iterations?: number; + keylen?: number; + encoding?: string; + digestAlgorithm?: string; + passwordValidator?: (password: string, cb: (err: any) => void) => void; + + usernameField?: string; + usernameUnique?: boolean; + + usernameQueryFields: Array; + + usernameLowerCase?: boolean; + + hashField?: string; + saltField?: string; + + limitAttempts?: boolean; + lastLoginField?: string; + attemptsField?: string; + interval?: number; + maxInterval?: number; + maxAttempts?: number; + + errorMessages?: PassportLocalErrorMessages; + } + + export interface PassportLocalSchema extends Schema { + plugin( + plugin: (schema: PassportLocalSchema, options?: PassportLocalOptions) => void, + options?: PassportLocalOptions + ): this; + } + + export function model( + name: string, + schema?: PassportLocalSchema, + collection?: string, + skipInit?: boolean): Statics & PassportLocalModel; +} + +declare module 'passport-local-mongoose' { + import mongoose = require('mongoose'); + var _: (schema: mongoose.Schema, options?: Object) => void; + export = _; +} From c33fce7326815671fae64b7b300a2ecd4b0a0727 Mon Sep 17 00:00:00 2001 From: linusbrolin Date: Tue, 9 Aug 2016 13:55:15 +0200 Subject: [PATCH 040/564] Added header --- mongoose-paginate/mongoose-paginate.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/mongoose-paginate/mongoose-paginate.d.ts b/mongoose-paginate/mongoose-paginate.d.ts index 48b0282bb4..9b90c1012e 100644 --- a/mongoose-paginate/mongoose-paginate.d.ts +++ b/mongoose-paginate/mongoose-paginate.d.ts @@ -1,3 +1,7 @@ +// Type definitions for mongoose-paginate 5.0.0 +// Project: https://github.com/edwardhotchkiss/mongoose-paginate +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + /// declare module 'mongoose' { From 0bb4aa560e9838fccc2a8bbac2d8b0f834e57e2c Mon Sep 17 00:00:00 2001 From: linusbrolin Date: Tue, 9 Aug 2016 13:59:13 +0200 Subject: [PATCH 041/564] Added more information to header --- mongoose-paginate/mongoose-paginate.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/mongoose-paginate/mongoose-paginate.d.ts b/mongoose-paginate/mongoose-paginate.d.ts index 9b90c1012e..5481c42775 100644 --- a/mongoose-paginate/mongoose-paginate.d.ts +++ b/mongoose-paginate/mongoose-paginate.d.ts @@ -1,5 +1,6 @@ // Type definitions for mongoose-paginate 5.0.0 // Project: https://github.com/edwardhotchkiss/mongoose-paginate +// Definitions by: Linus Brolin , simonxca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// From 096eda0b3d8fd58b96f727150ce2d58e43554f70 Mon Sep 17 00:00:00 2001 From: linusbrolin Date: Tue, 9 Aug 2016 14:03:19 +0200 Subject: [PATCH 042/564] Added header --- passport-local-mongoose/passport-local-mongoose.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts index c0fd0bf6de..8830a927ff 100644 --- a/passport-local-mongoose/passport-local-mongoose.d.ts +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -1,3 +1,8 @@ +// Type definitions for passport-local-mongoose 4.0.0 +// Project: https://github.com/saintedlama/passport-local-mongoose +// Definitions by: Linus Brolin , simonxca +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + /// /// From 276a66f8e0bc20135ae5bf89733c556407b33070 Mon Sep 17 00:00:00 2001 From: linusbrolin Date: Tue, 9 Aug 2016 15:22:45 +0200 Subject: [PATCH 043/564] Added tests --- .../passport-local-mongoose-tests.ts | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 passport-local-mongoose/passport-local-mongoose-tests.ts diff --git a/passport-local-mongoose/passport-local-mongoose-tests.ts b/passport-local-mongoose/passport-local-mongoose-tests.ts new file mode 100644 index 0000000000..8bdf0dded5 --- /dev/null +++ b/passport-local-mongoose/passport-local-mongoose-tests.ts @@ -0,0 +1,133 @@ +/// + +/** + * Created by Linus Brolin . + */ + +import { + Schema, + model, + PassportLocalDocument, + PassportLocalSchema, + PassportLocalModel, + PassportLocalOptions, + PassportLocalErrorMessages +} from 'mongoose'; +import * as passportLocalMongoose from 'passport-local-mongoose'; + +import { Router, Request, Response } from 'express'; +import * as passport from 'passport'; +import { Strategy as LocalStrategy } from 'passport-local'; + + +//#region Test Models +interface User extends PassportLocalDocument { + _id: string; + username: string; + hash: string; + salt: string; + attempts: number; + last: Date; +} + +const UserSchema: PassportLocalSchema = new Schema({ + username: String, + hash: String, + salt: String, + attempts: Number, + last: Date +}); + +let options: PassportLocalOptions = {}; +options.iterations = 25000; +options.keylen = 512; +options.digestAlgorithm = 'sha256'; +options.interval = 100; +options.usernameField = 'username'; +options.usernameUnique = true; +options.usernameLowerCase = true; +options.hashField = 'hash'; +options.saltField = 'salt'; +options.saltlen = 32; +options.attemptsField = 'attempts'; +options.lastLoginField = 'last'; +// TODO: +// options.selectFields = 'undefined'; +// options.populateFields = 'undefined'; +options.encoding = 'hex'; +options.limitAttempts = false; +options.maxAttempts = Infinity; +options.passwordValidator = function(password: string, cb: (err: any) => void): void {}; +options.usernameQueryFields = []; + +let errorMessages: PassportLocalErrorMessages = {}; +errorMessages.MissingPasswordError = 'No password was given'; +errorMessages.AttemptTooSoonError = 'Account is currently locked. Try again later'; +errorMessages.TooManyAttemptsError = 'Account locked due to too many failed login attempts'; +errorMessages.NoSaltValueStoredError = 'Authentication not possible. No salt value stored'; +errorMessages.IncorrectPasswordError = 'Password or username are incorrect'; +errorMessages.IncorrectUsernameError = 'Password or username are incorrect'; +errorMessages.MissingUsernameError = 'No username was given'; +errorMessages.UserExistsError = 'A user with the given username is already registered'; + +options.errorMessages = errorMessages; + +UserSchema.plugin(passportLocalMongoose, options); + +type UserModel = _UserModel & PassportLocalModel; +interface _UserModel {} + +let UserModel: UserModel = model('User', UserSchema) as UserModel; +//#endregion + + +//#region Test Passport/Passport-Local +passport.use(UserModel.createStrategy()); + +passport.use('login', new LocalStrategy({ + passReqToCallback: true, + usernameField: 'username', + passwordField: 'password' + }, + (req: any, username: string, password: string, done: (err: any, res: any, msg?: any) => void) => { + process.nextTick(() => { + UserModel + .findOne({ 'username': username }) + .exec((err: any, user: model) => { + if (err) { + console.log(err); + return done(err, null); + } + + if (!user) { + console.log(errorMessages.IncorrectUsernameError); + return done(null, false, errorMessages.IncorrectUsernameError); + } + + user.authenticate(password, function(autherr: any, authuser: User, autherrmsg: any) { + if (autherr) { + console.log(autherr); + return done(autherr, null); + } + + if (!authuser) { + console.log(errorMessages.IncorrectPasswordError); + return done(null, false, errorMessages.IncorrectPasswordError); + } + + return done(null, authuser); + }); + }); + }); + }) +); + +passport.serializeUser(UserModel.serializeUser()); +passport.deserializeUser(UserModel.deserializeUser()); + +let router: Router = Router(); + +router.post('/login', passport.authenticate('local'), function(req: Request, res: Response) { + res.redirect('/'); +}); +//#endregion From a8ad49221dbae4b50c0bdf0ba523c1ac69184802 Mon Sep 17 00:00:00 2001 From: linusbrolin Date: Tue, 9 Aug 2016 16:01:27 +0200 Subject: [PATCH 044/564] Added reference paths --- passport-local-mongoose/passport-local-mongoose-tests.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/passport-local-mongoose/passport-local-mongoose-tests.ts b/passport-local-mongoose/passport-local-mongoose-tests.ts index 8bdf0dded5..24e2bb9076 100644 --- a/passport-local-mongoose/passport-local-mongoose-tests.ts +++ b/passport-local-mongoose/passport-local-mongoose-tests.ts @@ -1,4 +1,7 @@ /// +/// +/// +/// /** * Created by Linus Brolin . From d482fccde9bf30517fa5729760e4f1d56d66c3c2 Mon Sep 17 00:00:00 2001 From: linusbrolin Date: Tue, 9 Aug 2016 16:44:02 +0200 Subject: [PATCH 045/564] Added tests --- mongoose-paginate/mongoose-paginate-tests.ts | 75 ++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 mongoose-paginate/mongoose-paginate-tests.ts diff --git a/mongoose-paginate/mongoose-paginate-tests.ts b/mongoose-paginate/mongoose-paginate-tests.ts new file mode 100644 index 0000000000..7857ffda33 --- /dev/null +++ b/mongoose-paginate/mongoose-paginate-tests.ts @@ -0,0 +1,75 @@ +/// +/// +/// + +/** + * Created by Linus Brolin . + */ + +import { + Schema, + model, + PaginateModel, + PaginateOptions, + PaginateResult +} from 'mongoose'; +import * as mongoosePaginate from 'mongoose-paginate'; +import { Router, Request, Response } from 'express'; + + +//#region Test Models +interface User { + email: string; + username: string; + password: string; +} + +const UserSchema: Schema = new Schema({ + email: String, + username: String, + password: String +}); + +UserSchema.plugin(mongoosePaginate); + +type UserModel = _UserModel & PaginateModel; +interface _UserModel {} + +let UserModel: UserModel = model('User', UserSchema) as UserModel; +//#endregion + + +//#region Test Paginate +let router: Router = Router(); + +router.get('/users.json', function(req: Request, res: Response) { + let descending: boolean = true; + let options: PaginateOptions = {}; + options.select = 'email username'; + options.sort = { 'username': (descending ? -1 : 1) }; + options.populate = ''; + options.lean = true; + options.leanWithId = false; + options.offset = 0; + options.page = 1; + options.limit = 10; + + UserModel + .paginate({}, options, (err: any, value: PaginateResult) => { + if (err) { + console.log(err); + return res.status(500).send(err); + } + + console.log('total: ' + value.total); + console.log('limit: ' + value.limit); + console.log('page: ' + value.page); + console.log('pages: ' + value.pages); + console.log('offset: ' + value.offset); + console.log('docs: '); + console.dir(value.docs); + return res.json(value); + }); + +}); +//#endregion From 17765b050ae21b11066b5f6c9cf8d5726af69c8b Mon Sep 17 00:00:00 2001 From: linusbrolin Date: Tue, 9 Aug 2016 16:52:31 +0200 Subject: [PATCH 046/564] Added options for selectFields and populateFields, and mongoose reference --- passport-local-mongoose/passport-local-mongoose-tests.ts | 6 +++--- passport-local-mongoose/passport-local-mongoose.d.ts | 3 +++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/passport-local-mongoose/passport-local-mongoose-tests.ts b/passport-local-mongoose/passport-local-mongoose-tests.ts index 24e2bb9076..cf41176f08 100644 --- a/passport-local-mongoose/passport-local-mongoose-tests.ts +++ b/passport-local-mongoose/passport-local-mongoose-tests.ts @@ -2,6 +2,7 @@ /// /// /// +/// /** * Created by Linus Brolin . @@ -54,9 +55,8 @@ options.saltField = 'salt'; options.saltlen = 32; options.attemptsField = 'attempts'; options.lastLoginField = 'last'; -// TODO: -// options.selectFields = 'undefined'; -// options.populateFields = 'undefined'; +options.selectFields = 'undefined'; +options.populateFields = 'undefined'; options.encoding = 'hex'; options.limitAttempts = false; options.maxAttempts = Infinity; diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts index 8830a927ff..8e4a6bb777 100644 --- a/passport-local-mongoose/passport-local-mongoose.d.ts +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -52,6 +52,9 @@ declare module 'mongoose' { usernameQueryFields: Array; + selectFields?: string; + populateFields?: string; + usernameLowerCase?: boolean; hashField?: string; From 3e18cac5fc60ccb0091bce3115e64890865253d9 Mon Sep 17 00:00:00 2001 From: Garth Kidd Date: Wed, 10 Aug 2016 10:28:40 +1000 Subject: [PATCH 047/564] 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 048/564] 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 049/564] 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 050/564] 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 b5b1fd28260ad040a545e3841f1e0b5f8ac959e3 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Sat, 13 Aug 2016 18:38:52 +0300 Subject: [PATCH 051/564] Adding missing methods from SyntheticEvent --- react/react.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/react/react.d.ts b/react/react.d.ts index 691b9c7a0e..f3ce283545 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -278,6 +278,8 @@ declare namespace __React { preventDefault(): void; stopPropagation(): void; persist(): void; + isDefaultPrevented(): boolean; + isPropagationStopped(): boolean; target: EventTarget; timeStamp: Date; type: string; 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 052/564] 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 eb05cd3c8d1ac5c15df7ea4c961f92bf9e04cfa7 Mon Sep 17 00:00:00 2001 From: Nicholas Iannone Date: Mon, 15 Aug 2016 10:46:34 -0500 Subject: [PATCH 053/564] Added db-migrate and db-migrate/pg definitions. --- db-migrate-pg/db-migrate-pg-tests.ts | 411 +++++++++++++++++++++++++++ db-migrate-pg/db-migrate-pg.d.ts | 59 ++++ db-migrate/db-migrate-tests.ts | 322 +++++++++++++++++++++ db-migrate/db-migrate.d.ts | 150 ++++++++++ 4 files changed, 942 insertions(+) create mode 100644 db-migrate-pg/db-migrate-pg-tests.ts create mode 100644 db-migrate-pg/db-migrate-pg.d.ts create mode 100644 db-migrate/db-migrate-tests.ts create mode 100644 db-migrate/db-migrate.d.ts diff --git a/db-migrate-pg/db-migrate-pg-tests.ts b/db-migrate-pg/db-migrate-pg-tests.ts new file mode 100644 index 0000000000..ad2430440c --- /dev/null +++ b/db-migrate-pg/db-migrate-pg-tests.ts @@ -0,0 +1,411 @@ +// Test file for db-migrate-pg Definition file +/// + +import * as DbMigratePg from "DbMigratePg"; + +// Throw together a dummy driver +let db = {}; + +let callback = (err: any, response: any) => { + // Do nothing. +}; + +/// createTable(tableName, columnSpec, callback) +db.createTable('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}, callback); + +db.createTable('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}, callback); + +/// dropTable(tableName, [options,] callback) +db.dropTable('pets', callback); + +db.dropTable('pets', { ifExists: true }, callback); + +/// renameTable(tableName, newTableName, callback) +db.renameTable('pets', 'pets_OLD', callback); + +/// addColumn(tableName, columnName, columnSpec, callback) +db.addColumn('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}, callback); + +db.addColumn('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}, callback); + +/// renameColumn(tableName, oldColumnName, newColumnName, callback) +db.renameColumn('pets', 'id', 'pet_id', callback); + +/// changeColumn(tableName, columnName, columnSpec, callback) +db.changeColumn('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}, callback); + +/// addIndex(tableName, indexName, columns, [unique,] callback) +db.addIndex('pets', 'pets_eye_color_idx', ['eye_color'], callback); +db.addIndex('pets', 'pets_registration_code_idx', ['registration_code'], true, callback); + +/// addForeignKey(tableName, referencedTableName, keyName, fieldMapping, rules, callback) +db.addForeignKey('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}, callback); + +/// removeForeignKey(tableName, keyName, options, callback) +db.removeForeignKey('module_user', 'module_uer_module_id_foreign', callback); +db.removeForeignKey('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}, callback); + +/// insert(tableName, [columnNameArray,] valueArray, callback) +db.insert('module_user', ['first_name', 'last_name'], ['Test', 'Testerson'], callback); +db.insert('module_user', ['Test', 'Testerson'], callback); + +/// removeIndex([tableName,] indexName, callback) +db.removeIndex('pets', 'pets_eye_color_idx', callback); +db.removeIndex('pets_eye_color_idx', callback); + +/// runSql(sql, [params,] callback) +db.runSql('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +], callback); +db.runSql('DROP TABLE `pets`', callback); + +/// all(sql, [params,] callback) +db.all('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test'], callback); +db.all('SELECT * FROM `module_user`', callback); + +/// ========= +/// Async +/// ========= + +let onResolve = (result: any) => {}; + +/// createTableAsync(tableName, columnSpec) +db.createTableAsync('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}).then(onResolve); + +db.createTableAsync('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}).then(onResolve); + +/// dropTableAsync(tableName, [options]) +db.dropTableAsync('pets').then(onResolve); +db.dropTableAsync('pets', { ifExists: true }).then(onResolve); + +/// renameTableAsync(tableName, newTableName) +db.renameTableAsync('pets', 'pets_OLD').then(onResolve); + +/// addColumnAsync(tableName, columnName, columnSpec) +db.addColumnAsync('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}).then(onResolve); + +db.addColumnAsync('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}).then(onResolve); + +/// renameColumnAsync(tableName, oldColumnName, newColumnName) +db.renameColumnAsync('pets', 'id', 'pet_id').then(onResolve); + +/// changeColumnAsync(tableName, columnName, columnSpec) +db.changeColumnAsync('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}).then(onResolve); + +/// addIndexAsync(tableName, indexName, columns, [unique]) +db.addIndexAsync('pets', 'pets_eye_color_idx', ['eye_color']).then(onResolve); +db.addIndexAsync('pets', 'pets_registration_code_idx', ['registration_code'], true).then(onResolve); + +/// addForeignKeyAsync(tableName, referencedTableName, keyName, fieldMapping, rules) +db.addForeignKeyAsync('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}).then(onResolve); + +/// removeForeignKeyAsync(tableName, keyName, options) +db.removeForeignKeyAsync('module_user', 'module_uer_module_id_foreign').then(onResolve); +db.removeForeignKeyAsync('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}).then(onResolve); + +/// insertAsync(tableName, [columnNameArray,] valueArray) +db.insertAsync('module_user', ['first_name', 'last_name'], ['Test', 'Testerson']).then(onResolve); +db.insertAsync('module_user', ['Test', 'Testerson']).then(onResolve); + +/// removeIndexAsync([tableName,] indexName) +db.removeIndexAsync('pets', 'pets_eye_color_idx').then(onResolve); +db.removeIndexAsync('pets_eye_color_idx').then(onResolve); + +/// runSqlAsync(sql, [params]) +db.runSqlAsync('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +]).then(onResolve); +db.runSqlAsync('DROP TABLE `pets`').then(onResolve); + +/// allAsync(sql, [params]) +db.allAsync('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test']).then(onResolve); +db.allAsync('SELECT * FROM `module_user`').then(onResolve); + +/// ==================== +/// PG-specific tests +/// ==================== + +/// createColumnConstraint(spec, options, tableName, columnName) (INTERNAL USE ONLY) +let constraint: DbMigratePg.ColumnConstraint; + +constraint = db.createColumnConstraint({ + type: 'int', + length: 10, + unsigned: true, + primaryKey: false, + autoIncrement: false, + notNull: true, + unique: false, + defaultValue: 0, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + 'eye_color': 'id' + } + } +}, { + emitPrimaryKey: false +}, 'pets', 'eye_color'); + +// Print the SQL constraints +console.log(constraint.constraints); + +// Invoke the foreign key builder +constraint.foreignKey(callback); + +/// Public Callback Methods: + +/// createDatabase(dbName, [options,] callback) +db.createDatabase('petstore', callback); +db.createDatabase('petstore', {}, callback); + +/// dropDatabase(dbName, [options,] callback) +db.dropDatabase('petstore', callback); +db.dropDatabase('petstore', { ifExists: true }, callback); + +/// createSequence(sqName, [options,] callback) +db.createSequence('pets_id_sq', callback); +db.createSequence('pets_id_sq', { temp: true }, callback); + +/// switchDatabase(options, callback) +db.switchDatabase('petstore', callback); +db.switchDatabase({ database: 'petstore' }, callback); + +/// dropSequence(sqName, [options,] callback) +db.dropSequence('pets_id_sq', callback); +db.dropSequence('pets_id_sq', { + ifExists: true, + cascade: true, + restrict: true, +}, callback); + +/// Public Promisified Methods: + +/// createDatabaseAsync(dbName, [options]) +db.createDatabaseAsync('petstore').then(onResolve); +db.createDatabaseAsync('petstore', {}).then(onResolve); + +/// dropDatabaseAsync(dbName, [options]) +db.dropDatabaseAsync('petstore').then(onResolve); +db.dropDatabaseAsync('petstore', { ifExists: true }).then(onResolve); + +/// createSequenceAsync(sqName, [options]) +db.createSequenceAsync('pets_id_sq').then(onResolve); +db.createSequenceAsync('pets_id_sq', { temp: true }).then(onResolve); + +/// switchDatabaseAsync(options) +db.switchDatabaseAsync('petstore').then(onResolve); +db.switchDatabaseAsync({ database: 'petstore' }).then(onResolve); + +/// dropSequenceAsync(sqName, [options]) +db.dropSequenceAsync('pets_id_sq').then(onResolve); +db.dropSequenceAsync('pets_id_sq', { + ifExists: true, + cascade: true, + restrict: true, +}).then(onResolve); diff --git a/db-migrate-pg/db-migrate-pg.d.ts b/db-migrate-pg/db-migrate-pg.d.ts new file mode 100644 index 0000000000..056c0c71ce --- /dev/null +++ b/db-migrate-pg/db-migrate-pg.d.ts @@ -0,0 +1,59 @@ +// Type definitions for db-migrate-pg +// Project: https://github.com/db-migrate/pg +// Definitions by: nickiannone https://github.com/nickiannone +// Definitions: https://github.com/nickiannone/DefinitelyTyped + +/// +/// + +declare module "DbMigratePg" { + + import * as pg from "pg"; + import * as DbMigrate from "DbMigrate"; + + // Yes, this is a dummy interface for now; the current implementation of the pg driver doesn't need any options. + export interface CreateDatabaseOptions {} + + export interface DropDatabaseOptions { + ifExists?: boolean; + } + + export interface CreateSequenceOptions { + temp?: boolean; + } + + export interface SwitchDatabaseOptions { + database?: string; + } + + export interface DropSequenceOptions { + ifExists?: boolean; + cascade?: boolean; + restrict?: boolean; + } + + export interface ColumnConstraint { + foreignKey: (callback: DbMigrate.CallbackFunction) => void; + constraints: string; + } + + export interface ColumnConstraintOptions { + emitPrimaryKey?: boolean; + } + + export class PgDriver extends DbMigrate.Base { + constructor(connection: pg.Client, schema: string, intern: DbMigrate.InternalOptions); + createDatabase(dbName: string, optionsOrCb: CreateDatabaseOptions | DbMigrate.CallbackFunction, callback?: DbMigrate.CallbackFunction): void; + dropDatabase(dbName: string, optionsOrCb: DropDatabaseOptions | DbMigrate.CallbackFunction, callback?: DbMigrate.CallbackFunction): void; + createSequence(sqName: string, optionsOrCb: CreateSequenceOptions | DbMigrate.CallbackFunction, callback?: DbMigrate.CallbackFunction): void; + switchDatabase(options: string | SwitchDatabaseOptions, callback: DbMigrate.CallbackFunction): void; + dropSequence(dbName: string, optionsOrCb: DropSequenceOptions | DbMigrate.CallbackFunction, callback?: DbMigrate.CallbackFunction): void; + createColumnConstraint(spec: DbMigrate.ColumnSpec, options: ColumnConstraintOptions, tableName: string, columnName: string): ColumnConstraint; + + createDatabaseAsync(dbName: string, options?: CreateDatabaseOptions): Promise; + dropDatabaseAsync(dbName: string, options?: DropDatabaseOptions): Promise; + createSequenceAsync(sqName: string, options?: CreateSequenceOptions): Promise; + switchDatabaseAsync(options: string | SwitchDatabaseOptions): Promise; + dropSequenceAsync(dbName: string, options?: DropSequenceOptions): Promise; + } +} \ No newline at end of file diff --git a/db-migrate/db-migrate-tests.ts b/db-migrate/db-migrate-tests.ts new file mode 100644 index 0000000000..9bdaafed5b --- /dev/null +++ b/db-migrate/db-migrate-tests.ts @@ -0,0 +1,322 @@ +// Test file for db.js Definition file +/// + +import * as DbMigrate from "DbMigrate"; + +// Throw together a dummy driver +let db = {}; + +let callback = (err: any, response: any) => { + // Do nothing. +}; + +/// createTable(tableName, columnSpec, callback) +db.createTable('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}, callback); + +db.createTable('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}, callback); + +/// dropTable(tableName, [options,] callback) +db.dropTable('pets', callback); + +db.dropTable('pets', { ifExists: true }, callback); + +/// renameTable(tableName, newTableName, callback) +db.renameTable('pets', 'pets_OLD', callback); + +/// addColumn(tableName, columnName, columnSpec, callback) +db.addColumn('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}, callback); + +db.addColumn('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}, callback); + +/// renameColumn(tableName, oldColumnName, newColumnName, callback) +db.renameColumn('pets', 'id', 'pet_id', callback); + +/// changeColumn(tableName, columnName, columnSpec, callback) +db.changeColumn('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}, callback); + +/// addIndex(tableName, indexName, columns, [unique,] callback) +db.addIndex('pets', 'pets_eye_color_idx', ['eye_color'], callback); +db.addIndex('pets', 'pets_registration_code_idx', ['registration_code'], true, callback); + +/// addForeignKey(tableName, referencedTableName, keyName, fieldMapping, rules, callback) +db.addForeignKey('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}, callback); + +/// removeForeignKey(tableName, keyName, options, callback) +db.removeForeignKey('module_user', 'module_uer_module_id_foreign', callback); +db.removeForeignKey('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}, callback); + +/// insert(tableName, [columnNameArray,] valueArray, callback) +db.insert('module_user', ['first_name', 'last_name'], ['Test', 'Testerson'], callback); +db.insert('module_user', ['Test', 'Testerson'], callback); + +/// removeIndex([tableName,] indexName, callback) +db.removeIndex('pets', 'pets_eye_color_idx', callback); +db.removeIndex('pets_eye_color_idx', callback); + +/// runSql(sql, [params,] callback) +db.runSql('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +], callback); +db.runSql('DROP TABLE `pets`', callback); + +/// all(sql, [params,] callback) +db.all('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test'], callback); +db.all('SELECT * FROM `module_user`', callback); + +/// ========= +/// Async +/// ========= + +let onResolve = (result: any) => {}; + +/// createTableAsync(tableName, columnSpec) +db.createTableAsync('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}).then(onResolve); + +db.createTableAsync('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}).then(onResolve); + +/// dropTableAsync(tableName, [options]) +db.dropTableAsync('pets').then(onResolve); +db.dropTableAsync('pets', { ifExists: true }).then(onResolve); + +/// renameTableAsync(tableName, newTableName) +db.renameTableAsync('pets', 'pets_OLD').then(onResolve); + +/// addColumnAsync(tableName, columnName, columnSpec) +db.addColumnAsync('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}).then(onResolve); + +db.addColumnAsync('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}).then(onResolve); + +/// renameColumnAsync(tableName, oldColumnName, newColumnName) +db.renameColumnAsync('pets', 'id', 'pet_id').then(onResolve); + +/// changeColumnAsync(tableName, columnName, columnSpec) +db.changeColumnAsync('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}).then(onResolve); + +/// addIndexAsync(tableName, indexName, columns, [unique]) +db.addIndexAsync('pets', 'pets_eye_color_idx', ['eye_color']).then(onResolve); +db.addIndexAsync('pets', 'pets_registration_code_idx', ['registration_code'], true).then(onResolve); + +/// addForeignKeyAsync(tableName, referencedTableName, keyName, fieldMapping, rules) +db.addForeignKeyAsync('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}).then(onResolve); + +/// removeForeignKeyAsync(tableName, keyName, options) +db.removeForeignKeyAsync('module_user', 'module_uer_module_id_foreign').then(onResolve); +db.removeForeignKeyAsync('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}).then(onResolve); + +/// insertAsync(tableName, [columnNameArray,] valueArray) +db.insertAsync('module_user', ['first_name', 'last_name'], ['Test', 'Testerson']).then(onResolve); +db.insertAsync('module_user', ['Test', 'Testerson']).then(onResolve); + +/// removeIndexAsync([tableName,] indexName) +db.removeIndexAsync('pets', 'pets_eye_color_idx').then(onResolve); +db.removeIndexAsync('pets_eye_color_idx').then(onResolve); + +/// runSqlAsync(sql, [params]) +db.runSqlAsync('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +]).then(onResolve); +db.runSqlAsync('DROP TABLE `pets`').then(onResolve); + +/// allAsync(sql, [params]) +db.allAsync('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test']).then(onResolve); +db.allAsync('SELECT * FROM `module_user`').then(onResolve); \ No newline at end of file diff --git a/db-migrate/db-migrate.d.ts b/db-migrate/db-migrate.d.ts new file mode 100644 index 0000000000..465dfb1c68 --- /dev/null +++ b/db-migrate/db-migrate.d.ts @@ -0,0 +1,150 @@ +/// +/// + +// Type definitions for db-migrate/db-migrate-base +// Project: https://github.com/db-migrate/db-migrate-base +// Definitions by: nickiannone https://github.com/nickiannone +// Definitions: https://github.com/nickiannone/DefinitelyTyped + +declare module "DbMigrate" { + + export interface CallbackFunction { (err: any, response: any): void; } + + export interface InternalModule { + log: any; + type: any; + } + + export interface InternalOptions { + mod: InternalModule; + } + + export interface ColumnSpec { + length?: number; + type: string; + unsigned?: boolean; + primaryKey?: boolean; + autoIncrement?: boolean; + notNull?: boolean; + unique?: boolean; + defaultValue?: any; + foreignKey?: ForeignKeySpec; + } + + export interface ForeignKeySpec { + name: string; + table: string; + rules?: ForeignKeyRules; + mapping: string | any; + } + + export interface ForeignKeyRules { + onDelete: string; + onUpdate: string; + } + + export interface RemoveForeignKeyOptions { + dropIndex?: boolean; + } + + export interface ColumnDef { + foreignKey?: any; // TODO Figure this out! + constraints: string; + } + + export interface CreateTableOptions { + columns?: Array; + ifNotExists?: boolean; + } + + export interface DropTableOptions { + ifExists?: boolean; + } + + export class Base { + constructor(intern: InternalOptions); + + close(callback?: CallbackFunction): void; + mapDataType(str: string): string; + truncate(tableName: string, callback: CallbackFunction): void; + checkDBMS(dbms: any, callback: CallbackFunction): void; + createDatabase(...options: any[]): void; + switchDatabase(...options: any[]): void; + dropDatabase(...options: any[]): void; + recurseCallbackArray(foreignKeys: Array, callback: CallbackFunction): void; + bindForeignKey(tableName: string, columnName: string, fkOptions: ForeignKeySpec): (callback: CallbackFunction) => void; + createColumnDef(name: string, spec: ColumnSpec, options?: any): ColumnDef; // TODO Figure out a type for `options`! + //createColumnConstraint(spec: ColumnSpec, options?: any, ...implementationDefinedOptions: any[]): string; + createMigrationsTable(callback: CallbackFunction): void; + createSeedsTable(callback: CallbackFunction): void; + createTable(tableName: string, options: any | CreateTableOptions, callback: CallbackFunction): void; + dropTable(tableName: string, optionsOrCb?: DropTableOptions | CallbackFunction, callback?: CallbackFunction): void; + renameTable(tableName: string, newTableName: string, callback: CallbackFunction): void; + addColumn(tableName: string, columnName: string, columnSpec: ColumnSpec, callback: CallbackFunction): void; + removeColumn(tableName: string, columnName: string, callback: CallbackFunction): void; + renameColumn(tableName: string, oldColumnName: string, newColumnName: string, callback: CallbackFunction): void; + changeColumn(tableName: string, columnName: string, columnSpec: ColumnSpec, callback: CallbackFunction): void; + quoteDDLArr(arr: Array): Array; + quoteArr(arr: Array): Array; + addIndex(tableName: string, indexName: string, columns: string | Array, uniqueOrCb?: boolean | CallbackFunction, callback?: CallbackFunction): void; + insert(tableName: string, columnNameOrValueArray: any, valueArrayOrCb?: any | CallbackFunction, callback?: CallbackFunction): void; + update(tableName: string, columnNameOrValueArray: any, valueArrayOrIds?: any, idsOrCb?: any | CallbackFunction, callback?: CallbackFunction): void; + lookup(tableName: string, column: string, id?: any, callback?: CallbackFunction): void; + removeIndex(tableNameOrIndexName: string, indexNameOrCb?: string | CallbackFunction, callback?: CallbackFunction): void; + addForeignKey(tableName: string, referencedTableName: string, keyName: string, fieldMapping: any, rules: ForeignKeyRules, callback: CallbackFunction): void; + removeForeignKey(tableName: string, keyName: string, optionsOrCb?: RemoveForeignKeyOptions | CallbackFunction, callback?: CallbackFunction): void; + normalizeColumnSpec(spec: string | ColumnSpec): ColumnSpec; + addMigrationRecord(name: string, callback: CallbackFunction): void; + addSeedRecord(name: string, callback: CallbackFunction): void; + startMigration(callback: CallbackFunction): void; + endMigration(callback: CallbackFunction): void; + runSql(sql?: string, paramsOrCb?: Array | CallbackFunction, callback?: CallbackFunction): void; + allLoadedMigrations(callback: CallbackFunction): void; + allLoadedSeeds(callback: CallbackFunction): void; + deleteMigration(migrationName: string, callback: CallbackFunction): void; + remove(table: string, ids: any, callback: CallbackFunction): void; // TODO Make ids match the type of ids in buildWhereClause(ids); + buildWhereClause(ids: any): string; + deleteSeed(seedName: string, callback: CallbackFunction): void; + all(sql: string, paramsOrCb?: Array | CallbackFunction, callback?: CallbackFunction): void; + escape(str: string): string; + escapeString(str: string): string; + escapeDDL(str: string): string; + + // Promisified methods + closeAsync(): Promise; + truncateAsync(tableName: string): Promise; + checkDBMSAsync(dbms: any): Promise; + createDatabaseAsync(...options: any[]): Promise; + switchDatabaseAsync(...options: any[]): Promise; + dropDatabaseAsync(...options: any[]): Promise; + recurseCallbackArrayAsync(foreignKeys: Array): Promise; + createMigrationsTableAsync(): Promise; + createSeedsTableAsync(): Promise; + createTableAsync(tableName: string, options: any | CreateTableOptions): Promise; + dropTableAsync(tableName: string, options?: DropTableOptions): Promise; + renameTableAsync(tableName: string, newTableName: string): Promise; + addColumnAsync(tableName: string, columnName: string, columnSpec: ColumnSpec): Promise; + removeColumnAsync(tableName: string, columnName: string): Promise; + renameColumnAsync(tableName: string, oldColumnName: string, newColumnName: string): Promise; + changeColumnAsync(tableName: string, columnName: string, columnSpec: ColumnSpec): Promise; + addIndexAsync(tableName: string, indexName: string, columns: string | Array, unique?: boolean): Promise; + insertAsync(tableName: string, columnNameOrValueArray: any, valueArrayOrCb?: any | CallbackFunction, callback?: CallbackFunction): Promise; + updateAsync(tableName: string, columnNameOrValueArray: any, valueArrayOrIds?: any, idsOrCb?: any | CallbackFunction, callback?: CallbackFunction): Promise; + lookupAsync(tableName: string, column: string, id?: any, callback?: CallbackFunction): Promise; + removeIndexAsync(tableNameOrIndexName: string, indexName?: string): Promise; + addForeignKeyAsync(tableName: string, referencedTableName: string, keyName: string, fieldMapping: any, rules: ForeignKeyRules): Promise; + removeForeignKeyAsync(tableName: string, keyName: string, options?: RemoveForeignKeyOptions): Promise; + addMigrationRecordAsync(name: string): Promise; + addSeedRecordAsync(name: string): Promise; + startMigrationAsync(): Promise; + endMigrationAsync(callback: CallbackFunction): Promise; + runSqlAsync(sql?: string, params?: Array): Promise; + allLoadedMigrationsAsync(): Promise; + allLoadedSeedsAsync(): Promise; + deleteMigrationAsync(migrationName: string): Promise; + removeAsync(table: string, ids: any): Promise; + deleteSeedAsync(seedName: string): Promise; + allAsync(sql: string, params?: Array): Promise; + } + +} \ No newline at end of file From 3b17086389f9ff0441376735df25f7ad0ee861ca Mon Sep 17 00:00:00 2001 From: Nicholas Iannone Date: Mon, 15 Aug 2016 11:39:47 -0500 Subject: [PATCH 054/564] Fix headers. --- db-migrate-pg/db-migrate-pg.d.ts | 2 +- db-migrate/db-migrate.d.ts | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/db-migrate-pg/db-migrate-pg.d.ts b/db-migrate-pg/db-migrate-pg.d.ts index 056c0c71ce..23e9025a21 100644 --- a/db-migrate-pg/db-migrate-pg.d.ts +++ b/db-migrate-pg/db-migrate-pg.d.ts @@ -1,6 +1,6 @@ // Type definitions for db-migrate-pg // Project: https://github.com/db-migrate/pg -// Definitions by: nickiannone https://github.com/nickiannone +// Definitions by: nickiannone // Definitions: https://github.com/nickiannone/DefinitelyTyped /// diff --git a/db-migrate/db-migrate.d.ts b/db-migrate/db-migrate.d.ts index 465dfb1c68..88223ca4b0 100644 --- a/db-migrate/db-migrate.d.ts +++ b/db-migrate/db-migrate.d.ts @@ -1,11 +1,11 @@ -/// -/// - -// Type definitions for db-migrate/db-migrate-base +// Type definitions for db-migrate-base // Project: https://github.com/db-migrate/db-migrate-base -// Definitions by: nickiannone https://github.com/nickiannone +// Definitions by: nickiannone // Definitions: https://github.com/nickiannone/DefinitelyTyped +/// +/// + declare module "DbMigrate" { export interface CallbackFunction { (err: any, response: any): void; } From 2c5dc32b68c0a022a3b7a1c46e8bd8878ca57da6 Mon Sep 17 00:00:00 2001 From: Nicholas Iannone Date: Mon, 15 Aug 2016 11:42:00 -0500 Subject: [PATCH 055/564] Tweaked name to match npm --- db-migrate/db-migrate.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db-migrate/db-migrate.d.ts b/db-migrate/db-migrate.d.ts index 88223ca4b0..66b4515f30 100644 --- a/db-migrate/db-migrate.d.ts +++ b/db-migrate/db-migrate.d.ts @@ -1,5 +1,5 @@ -// Type definitions for db-migrate-base -// Project: https://github.com/db-migrate/db-migrate-base +// Type definitions for db-migrate +// Project: https://github.com/db-migrate/db-migrate // Definitions by: nickiannone // Definitions: https://github.com/nickiannone/DefinitelyTyped From 2675fa3a2e380e114181e5be481b32ed5269ec4c Mon Sep 17 00:00:00 2001 From: Nicholas Iannone Date: Mon, 15 Aug 2016 12:04:09 -0500 Subject: [PATCH 056/564] Fixed package name and project link --- .../db-migrate-base-tests.ts | 8 +++---- .../db-migrate-base.d.ts | 6 ++--- db-migrate-pg/db-migrate-pg.d.ts | 22 +++++++++---------- 3 files changed, 18 insertions(+), 18 deletions(-) rename db-migrate/db-migrate-tests.ts => db-migrate-base/db-migrate-base-tests.ts (97%) rename db-migrate/db-migrate.d.ts => db-migrate-base/db-migrate-base.d.ts (98%) diff --git a/db-migrate/db-migrate-tests.ts b/db-migrate-base/db-migrate-base-tests.ts similarity index 97% rename from db-migrate/db-migrate-tests.ts rename to db-migrate-base/db-migrate-base-tests.ts index 9bdaafed5b..68c61e6f6c 100644 --- a/db-migrate/db-migrate-tests.ts +++ b/db-migrate-base/db-migrate-base-tests.ts @@ -1,10 +1,10 @@ -// Test file for db.js Definition file -/// +// Test file for db-migrate-base Definition file +/// -import * as DbMigrate from "DbMigrate"; +import * as DbMigrateBase from "DbMigrateBase"; // Throw together a dummy driver -let db = {}; +let db = {}; let callback = (err: any, response: any) => { // Do nothing. diff --git a/db-migrate/db-migrate.d.ts b/db-migrate-base/db-migrate-base.d.ts similarity index 98% rename from db-migrate/db-migrate.d.ts rename to db-migrate-base/db-migrate-base.d.ts index 66b4515f30..47dd8ce1c2 100644 --- a/db-migrate/db-migrate.d.ts +++ b/db-migrate-base/db-migrate-base.d.ts @@ -1,12 +1,12 @@ -// Type definitions for db-migrate -// Project: https://github.com/db-migrate/db-migrate +// Type definitions for db-migrate-base +// Project: https://github.com/db-migrate/db-migrate-base // Definitions by: nickiannone // Definitions: https://github.com/nickiannone/DefinitelyTyped /// /// -declare module "DbMigrate" { +declare module "DbMigrateBase" { export interface CallbackFunction { (err: any, response: any): void; } diff --git a/db-migrate-pg/db-migrate-pg.d.ts b/db-migrate-pg/db-migrate-pg.d.ts index 23e9025a21..4d2823ec52 100644 --- a/db-migrate-pg/db-migrate-pg.d.ts +++ b/db-migrate-pg/db-migrate-pg.d.ts @@ -3,13 +3,13 @@ // Definitions by: nickiannone // Definitions: https://github.com/nickiannone/DefinitelyTyped -/// +/// /// declare module "DbMigratePg" { import * as pg from "pg"; - import * as DbMigrate from "DbMigrate"; + import * as DbMigrateBase from "DbMigrateBase"; // Yes, this is a dummy interface for now; the current implementation of the pg driver doesn't need any options. export interface CreateDatabaseOptions {} @@ -33,7 +33,7 @@ declare module "DbMigratePg" { } export interface ColumnConstraint { - foreignKey: (callback: DbMigrate.CallbackFunction) => void; + foreignKey: (callback: DbMigrateBase.CallbackFunction) => void; constraints: string; } @@ -41,14 +41,14 @@ declare module "DbMigratePg" { emitPrimaryKey?: boolean; } - export class PgDriver extends DbMigrate.Base { - constructor(connection: pg.Client, schema: string, intern: DbMigrate.InternalOptions); - createDatabase(dbName: string, optionsOrCb: CreateDatabaseOptions | DbMigrate.CallbackFunction, callback?: DbMigrate.CallbackFunction): void; - dropDatabase(dbName: string, optionsOrCb: DropDatabaseOptions | DbMigrate.CallbackFunction, callback?: DbMigrate.CallbackFunction): void; - createSequence(sqName: string, optionsOrCb: CreateSequenceOptions | DbMigrate.CallbackFunction, callback?: DbMigrate.CallbackFunction): void; - switchDatabase(options: string | SwitchDatabaseOptions, callback: DbMigrate.CallbackFunction): void; - dropSequence(dbName: string, optionsOrCb: DropSequenceOptions | DbMigrate.CallbackFunction, callback?: DbMigrate.CallbackFunction): void; - createColumnConstraint(spec: DbMigrate.ColumnSpec, options: ColumnConstraintOptions, tableName: string, columnName: string): ColumnConstraint; + export class PgDriver extends DbMigrateBase.Base { + constructor(connection: pg.Client, schema: string, intern: DbMigrateBase.InternalOptions); + createDatabase(dbName: string, optionsOrCb: CreateDatabaseOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + dropDatabase(dbName: string, optionsOrCb: DropDatabaseOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + createSequence(sqName: string, optionsOrCb: CreateSequenceOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + switchDatabase(options: string | SwitchDatabaseOptions, callback: DbMigrateBase.CallbackFunction): void; + dropSequence(dbName: string, optionsOrCb: DropSequenceOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + createColumnConstraint(spec: DbMigrateBase.ColumnSpec, options: ColumnConstraintOptions, tableName: string, columnName: string): ColumnConstraint; createDatabaseAsync(dbName: string, options?: CreateDatabaseOptions): Promise; dropDatabaseAsync(dbName: string, options?: DropDatabaseOptions): Promise; From 3b613b085dfe0f388310bedbc15726eeaea23ebd Mon Sep 17 00:00:00 2001 From: Daniel Pereira Date: Mon, 15 Aug 2016 13:25:00 -0500 Subject: [PATCH 057/564] Added electron-notify --- electron-notify/electron-notify-tests.ts | 0 electron-notify/electron-notify.d.ts | 27 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 electron-notify/electron-notify-tests.ts create mode 100644 electron-notify/electron-notify.d.ts diff --git a/electron-notify/electron-notify-tests.ts b/electron-notify/electron-notify-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/electron-notify/electron-notify.d.ts b/electron-notify/electron-notify.d.ts new file mode 100644 index 0000000000..3678c00e3d --- /dev/null +++ b/electron-notify/electron-notify.d.ts @@ -0,0 +1,27 @@ +// Type definitions for electron-notify v0.1.0 +// Project: https://github.com/hankbao/electron-notify +// Definitions by: Daniel Pereira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace ElectronNotify { +} + +/** Nice and simple notifications for electron apps */ +declare module 'electron-notifications' { + + /** Change some config options. Can be run multiple times, also between notify()-calls to change electron-notifys behaviour. */ + export function setConfig(configObj); + + /** Displays new notification. */ + export function notify(notificationObj); + + /** Clears the animation queue and closes all windows opened by electron-notify. Call this to clean up before quiting your app. */ + export function closeAll(); + + export function setTemplatePath(path); + + /** Returns the maximum amount of notifications that fit onto the users screen. */ + export function calcMaxVisibleNotification(): number; +} \ No newline at end of file From 07084d3ae632574dae4785a5caaaccde674527c9 Mon Sep 17 00:00:00 2001 From: Daniel Pereira Date: Mon, 15 Aug 2016 15:14:45 -0500 Subject: [PATCH 058/564] Wrong module name --- electron-notify/electron-notify.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/electron-notify/electron-notify.d.ts b/electron-notify/electron-notify.d.ts index 3678c00e3d..f6f4d47b07 100644 --- a/electron-notify/electron-notify.d.ts +++ b/electron-notify/electron-notify.d.ts @@ -9,7 +9,7 @@ declare namespace ElectronNotify { } /** Nice and simple notifications for electron apps */ -declare module 'electron-notifications' { +declare module 'electron-notify' { /** Change some config options. Can be run multiple times, also between notify()-calls to change electron-notifys behaviour. */ export function setConfig(configObj); From dd7de3e50c342bdf77de61d725083d3d20ab8d9e Mon Sep 17 00:00:00 2001 From: Daniel Pereira Date: Mon, 15 Aug 2016 15:57:19 -0500 Subject: [PATCH 059/564] Added INotification and IConfiguration to electron notify --- electron-notify/electron-notify-tests.ts | 23 +++++++++++++ electron-notify/electron-notify.d.ts | 42 +++++++++++++++++++++--- 2 files changed, 60 insertions(+), 5 deletions(-) diff --git a/electron-notify/electron-notify-tests.ts b/electron-notify/electron-notify-tests.ts index e69de29bb2..9194a11f1b 100644 --- a/electron-notify/electron-notify-tests.ts +++ b/electron-notify/electron-notify-tests.ts @@ -0,0 +1,23 @@ +/// + +import * as eNotify from 'electron-notify'; + +eNotify.setConfig({ + appIcon: 'images/otherIcon.png', + displayTime: 6000, + defaultStyleText: { + color: '#FF0000', + fontWeight: 'bold' + } +}); + +eNotify.notify({ + title: 'Title', + text: 'Some text', + image: 'path/to/image.png', + url: 'http://google.de', + sound: 'notification.wav', + onClickFunc: function () { console.log('onClick') }, + onShowFunc: function () { console.log('onShow') }, + onCloseFunc: function () { console.log('onClose') } +}); \ No newline at end of file diff --git a/electron-notify/electron-notify.d.ts b/electron-notify/electron-notify.d.ts index f6f4d47b07..d5ac7f1966 100644 --- a/electron-notify/electron-notify.d.ts +++ b/electron-notify/electron-notify.d.ts @@ -6,22 +6,54 @@ /// declare namespace ElectronNotify { + + interface INotification { + title: string, + text?: string, + image?: string, + url?: string, + sound?: string, + onClickFunc?: (event: string, id: number, closeNotification) => void, + onShowFunc?: (event: string, id: number, closeNotification) => void, + onCloseFunc?: (event: string, id: number) => void + } + + interface IConfiguration { + width?: number, + height?: number, + padding?: number, + borderRadius?: number, + displayTime?: number, + animationSteps?: number, + animationStepMs?: number, + animateInParallel?: boolean, + appIcon?: string, + pathToModule?: string, + logging?: boolean, + defaultWindow?: Electron.BrowserWindowOptions, + defaultStyleContainer?: any, + defaultStyleAppIcon?: any, + defaultStyleImage?: any, + defaultStyleClose?: any, + defaultStyleText?: any + } + } /** Nice and simple notifications for electron apps */ declare module 'electron-notify' { /** Change some config options. Can be run multiple times, also between notify()-calls to change electron-notifys behaviour. */ - export function setConfig(configObj); + export function setConfig(customConfig: ElectronNotify.IConfiguration); /** Displays new notification. */ - export function notify(notificationObj); + export function notify(notification: ElectronNotify.INotification); /** Clears the animation queue and closes all windows opened by electron-notify. Call this to clean up before quiting your app. */ export function closeAll(); - export function setTemplatePath(path); + export function getTemplatePath(): string; + + export function setTemplatePath(path: string); - /** Returns the maximum amount of notifications that fit onto the users screen. */ - export function calcMaxVisibleNotification(): number; } \ No newline at end of file From 8f082a028691948ef922e39ebc03b06e63f23518 Mon Sep 17 00:00:00 2001 From: Daniel Pereira Date: Mon, 15 Aug 2016 15:59:05 -0500 Subject: [PATCH 060/564] Return voids --- electron-notify/electron-notify.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/electron-notify/electron-notify.d.ts b/electron-notify/electron-notify.d.ts index d5ac7f1966..2984bd4876 100644 --- a/electron-notify/electron-notify.d.ts +++ b/electron-notify/electron-notify.d.ts @@ -44,16 +44,16 @@ declare namespace ElectronNotify { declare module 'electron-notify' { /** Change some config options. Can be run multiple times, also between notify()-calls to change electron-notifys behaviour. */ - export function setConfig(customConfig: ElectronNotify.IConfiguration); + export function setConfig(customConfig: ElectronNotify.IConfiguration): void; /** Displays new notification. */ - export function notify(notification: ElectronNotify.INotification); + export function notify(notification: ElectronNotify.INotification): void; /** Clears the animation queue and closes all windows opened by electron-notify. Call this to clean up before quiting your app. */ - export function closeAll(); + export function closeAll(): void; export function getTemplatePath(): string; - export function setTemplatePath(path: string); + export function setTemplatePath(path: string): void; } \ No newline at end of file From 306ceee471b09371f44e7daeaffb94ae92ec8b07 Mon Sep 17 00:00:00 2001 From: Daniel Pereira Date: Mon, 15 Aug 2016 15:59:55 -0500 Subject: [PATCH 061/564] Fix syntax issues --- electron-notify/electron-notify.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/electron-notify/electron-notify.d.ts b/electron-notify/electron-notify.d.ts index 2984bd4876..198f8cafb6 100644 --- a/electron-notify/electron-notify.d.ts +++ b/electron-notify/electron-notify.d.ts @@ -13,8 +13,8 @@ declare namespace ElectronNotify { image?: string, url?: string, sound?: string, - onClickFunc?: (event: string, id: number, closeNotification) => void, - onShowFunc?: (event: string, id: number, closeNotification) => void, + onClickFunc?: (event: string, id: number, closeNotification: any) => void, + onShowFunc?: (event: string, id: number, closeNotification: any) => void, onCloseFunc?: (event: string, id: number) => void } From a0d70238a7d366bbefcdbabd2c59ccbd63c32713 Mon Sep 17 00:00:00 2001 From: Daniel Pereira Date: Mon, 15 Aug 2016 16:45:28 -0500 Subject: [PATCH 062/564] Update events --- electron-notify/electron-notify-tests.ts | 9 ++++++--- electron-notify/electron-notify.d.ts | 15 ++++++++++++--- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/electron-notify/electron-notify-tests.ts b/electron-notify/electron-notify-tests.ts index 9194a11f1b..95e2edf998 100644 --- a/electron-notify/electron-notify-tests.ts +++ b/electron-notify/electron-notify-tests.ts @@ -17,7 +17,10 @@ eNotify.notify({ image: 'path/to/image.png', url: 'http://google.de', sound: 'notification.wav', - onClickFunc: function () { console.log('onClick') }, - onShowFunc: function () { console.log('onShow') }, - onCloseFunc: function () { console.log('onClose') } + onClickFunc: (event) => { + console.log('onClick ' + event.id); + event.closeNotification('onClick'); + }, + onShowFunc: (event) => { console.log('onShow ' + event.id) }, + onCloseFunc: (event) => { console.log('onClose ' + event.id) } }); \ No newline at end of file diff --git a/electron-notify/electron-notify.d.ts b/electron-notify/electron-notify.d.ts index 198f8cafb6..3ad6906205 100644 --- a/electron-notify/electron-notify.d.ts +++ b/electron-notify/electron-notify.d.ts @@ -7,15 +7,24 @@ declare namespace ElectronNotify { + interface ICloseNotificationEvent { + event: 'close' | 'show' | 'click', + id: number + } + + interface INotificationEvent extends ICloseNotificationEvent { + closeNotification: (reason: any) => void, + } + interface INotification { title: string, text?: string, image?: string, url?: string, sound?: string, - onClickFunc?: (event: string, id: number, closeNotification: any) => void, - onShowFunc?: (event: string, id: number, closeNotification: any) => void, - onCloseFunc?: (event: string, id: number) => void + onClickFunc?: (event: INotificationEvent) => void, + onShowFunc?: (event: INotificationEvent) => void, + onCloseFunc?: (event: ICloseNotificationEvent) => void } interface IConfiguration { From bf341749b4ebbd7242e452ef720ba2580316cf6c Mon Sep 17 00:00:00 2001 From: Erwin Poeze Date: Tue, 16 Aug 2016 08:38:54 +0200 Subject: [PATCH 063/564] 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 064/564] 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 065/564] 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 066/564] 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 067/564] 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 4595e61ad1e8c5f48255a016471487f100a818f8 Mon Sep 17 00:00:00 2001 From: minodisk Date: Tue, 16 Aug 2016 18:44:27 +0900 Subject: [PATCH 068/564] Update react-helmet - Add `titleTemplate` to `HelmetProps` - Remove blank lines --- react-helmet/react-helmet.d.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/react-helmet/react-helmet.d.ts b/react-helmet/react-helmet.d.ts index 2ea19ae469..553a69ed56 100644 --- a/react-helmet/react-helmet.d.ts +++ b/react-helmet/react-helmet.d.ts @@ -7,9 +7,10 @@ declare namespace ReactHelmet { import React = __React; - + interface HelmetProps { base?: any; + defaultTitle?: string; htmlAttributes?: any; link?: Array; meta?: Array; @@ -27,7 +28,7 @@ declare namespace ReactHelmet { script: HelmetDatum; title: HelmetDatum; } - + interface HelmetDatum { toString(): string; toComponent(): React.Component; @@ -41,6 +42,6 @@ declare module "react-helmet" { (): ReactHelmet.HelmetComponent rewind(): ReactHelmet.HelmetData } - + export = Helmet; } From 9bb6206f477a736748689cd95c8ed98468a3456f Mon Sep 17 00:00:00 2001 From: Lukas Zech Date: Tue, 16 Aug 2016 14:17:25 +0200 Subject: [PATCH 069/564] Add Buffer.swap16, Buffer.swap32 and Buffer.swap64 functions --- node/node-tests.ts | 8 ++++++++ node/node.d.ts | 3 +++ 2 files changed, 11 insertions(+) diff --git a/node/node-tests.ts b/node/node-tests.ts index 32bdc94fdb..e5e0a7397b 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -183,6 +183,14 @@ function bufferTests() { var result1 = Buffer.concat([utf8Buffer, base64Buffer]); var result2 = Buffer.concat([utf8Buffer, base64Buffer], 9999999); + // Class Methods: Buffer.swap16(), Buffer.swa32(), Buffer.swap64() + { + const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + buf.swap16(); + buf.swap32(); + buf.swap64(); + } + // Class Method: Buffer.from(array) { const buf: Buffer = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); diff --git a/node/node.d.ts b/node/node.d.ts index 99963bf49e..46e347d562 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -485,6 +485,9 @@ interface NodeBuffer extends Uint8Array { readFloatBE(offset: number, noAssert?: boolean): number; readDoubleLE(offset: number, noAssert?: boolean): number; readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; writeUInt8(value: number, offset: number, noAssert?: boolean): number; writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; From 4d8e6c5a4f2230652314f8e1cb6169b85ce33d02 Mon Sep 17 00:00:00 2001 From: Koloto Date: Tue, 16 Aug 2016 16:07:12 +0300 Subject: [PATCH 070/564] slickgrid: fixed getCellFromEvent signature, using DOMEvent in subscribe --- slickgrid/SlickGrid-tests.ts | 7 +++++-- slickgrid/SlickGrid.d.ts | 10 ++++++---- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/slickgrid/SlickGrid-tests.ts b/slickgrid/SlickGrid-tests.ts index e267a85948..592b966e6c 100644 --- a/slickgrid/SlickGrid-tests.ts +++ b/slickgrid/SlickGrid-tests.ts @@ -155,8 +155,6 @@ grid.getCellCssStyles("test")[0]["number_column"]; grid.getCellEditor(); -grid.getCellFromEvent(new Slick.Event()); - grid.getCellFromPoint(5, 10); grid.getCellNode(5, 10); @@ -210,3 +208,8 @@ columns.forEach(column => { grid.onSort.subscribe((e, args) => { var sortCol:string = args.sortCols[0].sortCol.field; }); + +grid.onMouseEnter.subscribe((e: DOMEvent, args) => { + let cell: Slick.Cell = args.grid.getCellFromEvent(e); + if (!cell) { return; } +}); \ No newline at end of file diff --git a/slickgrid/SlickGrid.d.ts b/slickgrid/SlickGrid.d.ts index 96f91eaaf1..bae31aab21 100644 --- a/slickgrid/SlickGrid.d.ts +++ b/slickgrid/SlickGrid.d.ts @@ -92,14 +92,16 @@ declare namespace Slick { * @method subscribe * @param fn {Function} Event handler. */ - public subscribe(fn: (eventData: EventData, data: T) => any ): void; + public subscribe(fn: (e: EventData, data: T) => any): void; + public subscribe(fn: (e: DOMEvent, data: T) => any): void; /*** * Removes an event handler added with subscribe(fn). * @method unsubscribe * @param fn {Function} Event handler to be removed. */ - public unsubscribe(fn: (eventData: EventData, data: T) => any ): void; + public unsubscribe(fn: (e: EventData, data: T) => any): void; + public unsubscribe(fn: (e: DOMEvent, data: T) => any): void; /*** * Fires an event notifying all subscribers. @@ -1037,7 +1039,7 @@ declare namespace Slick { * @param e A standard W3C/jQuery event. * @return **/ - public getCellFromEvent(e: Event): Cell; // todo: !! Unsure on return type !! + public getCellFromEvent(e: DOMEvent): Cell; /** * Returns a hash containing row and cell indexes. Coordinates are relative to the top left corner of the grid beginning with the first row (not including the column headers). @@ -1045,7 +1047,7 @@ declare namespace Slick { * @param y A y coordinate. * @return **/ - public getCellFromPoint(x: number, y: number): Cell; // todo: !! Unsure on return type !! + public getCellFromPoint(x: number, y: number): Cell; /** * Returns a DOM element containing a cell at a given row and cell. From f222c07219b1fad49639395dd32b0257d8480d1e Mon Sep 17 00:00:00 2001 From: Koloto Date: Tue, 16 Aug 2016 16:17:30 +0300 Subject: [PATCH 071/564] slickgrid: fixed getCellFromEvent signature, using DOMEvent in subscribe (fixed Travis CI failure) --- slickgrid/SlickGrid-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/slickgrid/SlickGrid-tests.ts b/slickgrid/SlickGrid-tests.ts index 592b966e6c..5221f7c19d 100644 --- a/slickgrid/SlickGrid-tests.ts +++ b/slickgrid/SlickGrid-tests.ts @@ -209,7 +209,7 @@ grid.onSort.subscribe((e, args) => { var sortCol:string = args.sortCols[0].sortCol.field; }); -grid.onMouseEnter.subscribe((e: DOMEvent, args) => { +grid.onMouseEnter.subscribe((e: DOMEvent, args: Slick.OnMouseEnterEventArgs) => { let cell: Slick.Cell = args.grid.getCellFromEvent(e); if (!cell) { return; } -}); \ No newline at end of file +}); From e847d83c47a87cc71909a77e228094977ed76d54 Mon Sep 17 00:00:00 2001 From: msucheck Date: Tue, 16 Aug 2016 15:35:02 +0200 Subject: [PATCH 072/564] Added useExternalSorting property to IGridOptions interface in ui-grid --- ui-grid/ui-grid.d.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index 1ce953885f..084a6ac17a 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -832,6 +832,11 @@ declare namespace uiGrid { * @default false */ useExternalFiltering?: boolean; + /** + * Disables client side sorting. When true, handle the sortChanged event and do the sorting there + * @default false + */ + useExternalSorting?: boolean; /** * Default time in milliseconds to throttle scroll events to, defaults to 70ms * @default 70 @@ -3558,7 +3563,7 @@ declare namespace uiGrid { * Algorithm to use for sorting this column. Takes 'a' and 'b' parameters * like any normal sorting function with additional 'rowA', 'rowB', and 'direction' * parameters that are the row objects and the current direction of the sort - * respectively. + * respectively. */ sortingAlgorithm?: (a: any, b: any, rowA: IGridRowOf, rowB: IGridRowOf, direction: string) => number; /** Column width */ @@ -3793,7 +3798,7 @@ declare namespace uiGrid { * Algorithm to use for sorting this column. Takes 'a' and 'b' parameters * like any normal sorting function with additional 'rowA', 'rowB', and 'direction' * parameters that are the row objects and the current direction of the sort - * respectively. + * respectively. */ sortingAlgorithm?: (a: any, b: any, rowA: IGridRowOf, rowB: IGridRowOf, direction: string) => number; /** From 0d1bc9c0da57e6bdb510dd86d5dd8e519ad06de8 Mon Sep 17 00:00:00 2001 From: msucheck Date: Tue, 16 Aug 2016 16:00:15 +0200 Subject: [PATCH 073/564] Added definitions for highcharts-more --- highcharts/highcharts-more.d.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 highcharts/highcharts-more.d.ts diff --git a/highcharts/highcharts-more.d.ts b/highcharts/highcharts-more.d.ts new file mode 100644 index 0000000000..1d42764b3c --- /dev/null +++ b/highcharts/highcharts-more.d.ts @@ -0,0 +1,12 @@ +// Type definitions for Highcharts 4.2.6 +// Project: http://www.highcharts.com/ +// Definitions by: Maciej Suchecki +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare var HighchartsMore: (H: HighchartsStatic) => HighchartsStatic; + +declare module "highcharts/highcharts-more" { + export = HighchartsMore; +} From a28758054fd5ee6d86e2f599e37e790a8c3a4e37 Mon Sep 17 00:00:00 2001 From: york yao Date: Tue, 16 Aug 2016 22:14:23 +0800 Subject: [PATCH 074/564] add 3 missing methods in crypto module: getCiphers, getCurves and getHashes --- node/node.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/node/node.d.ts b/node/node.d.ts index 99963bf49e..723f6daed4 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2166,6 +2166,9 @@ declare module "crypto" { } export function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer export function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer + export function getCiphers(): string[]; + export function getCurves(): string[]; + export function getHashes(): string[]; } declare module "stream" { From 0b7a922c8349ac89481ab8ef99b01cdd930287d6 Mon Sep 17 00:00:00 2001 From: msucheck Date: Tue, 16 Aug 2016 16:15:51 +0200 Subject: [PATCH 075/564] Added definitions for highcharts-modules-exporting --- highcharts/highcharts-modules-exporting.d.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 highcharts/highcharts-modules-exporting.d.ts diff --git a/highcharts/highcharts-modules-exporting.d.ts b/highcharts/highcharts-modules-exporting.d.ts new file mode 100644 index 0000000000..55368a7491 --- /dev/null +++ b/highcharts/highcharts-modules-exporting.d.ts @@ -0,0 +1,12 @@ +// Type definitions for Highcharts 4.2.6 (exporting module) +// Project: http://www.highcharts.com/ +// Definitions by: Maciej Suchecki +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare var HighchartsExporting: (H: HighchartsStatic) => HighchartsStatic; + +declare module "highcharts/highcharts-modules-exporting" { + export = HighchartsExporting; +} From 2fc3a43ab80b98afaabcc676e9de92517b3c2d35 Mon Sep 17 00:00:00 2001 From: msucheck Date: Tue, 16 Aug 2016 16:43:23 +0200 Subject: [PATCH 076/564] Fixed module name for Highcharts Exporting Module - fixes #10540 --- highcharts/highcharts-modules-exporting.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/highcharts/highcharts-modules-exporting.d.ts b/highcharts/highcharts-modules-exporting.d.ts index 55368a7491..4d3bdaa648 100644 --- a/highcharts/highcharts-modules-exporting.d.ts +++ b/highcharts/highcharts-modules-exporting.d.ts @@ -7,6 +7,6 @@ declare var HighchartsExporting: (H: HighchartsStatic) => HighchartsStatic; -declare module "highcharts/highcharts-modules-exporting" { +declare module "highcharts/modules/exporting" { export = HighchartsExporting; } From 00a6998f4e16aa2009ca5545768151d0e7ab7998 Mon Sep 17 00:00:00 2001 From: Daniel Pereira Date: Tue, 16 Aug 2016 10:10:39 -0500 Subject: [PATCH 077/564] Move interfaces in the 'electron-notify' module, and export them --- electron-notify/electron-notify.d.ts | 50 +++++++++++++--------------- 1 file changed, 23 insertions(+), 27 deletions(-) diff --git a/electron-notify/electron-notify.d.ts b/electron-notify/electron-notify.d.ts index 3ad6906205..b29efa0e50 100644 --- a/electron-notify/electron-notify.d.ts +++ b/electron-notify/electron-notify.d.ts @@ -5,29 +5,10 @@ /// -declare namespace ElectronNotify { +/** Nice and simple notifications for electron apps */ +declare module 'electron-notify' { - interface ICloseNotificationEvent { - event: 'close' | 'show' | 'click', - id: number - } - - interface INotificationEvent extends ICloseNotificationEvent { - closeNotification: (reason: any) => void, - } - - interface INotification { - title: string, - text?: string, - image?: string, - url?: string, - sound?: string, - onClickFunc?: (event: INotificationEvent) => void, - onShowFunc?: (event: INotificationEvent) => void, - onCloseFunc?: (event: ICloseNotificationEvent) => void - } - - interface IConfiguration { + export interface ICustomConfig { width?: number, height?: number, padding?: number, @@ -47,16 +28,31 @@ declare namespace ElectronNotify { defaultStyleText?: any } -} + export interface ICloseNotificationEvent { + event: 'close' | 'show' | 'click', + id: number + } -/** Nice and simple notifications for electron apps */ -declare module 'electron-notify' { + export interface INotificationEvent extends ICloseNotificationEvent { + closeNotification: (reason: any) => void, + } + + export interface INotification { + title: string, + text?: string, + image?: string, + url?: string, + sound?: string, + onClickFunc?: (event: INotificationEvent) => void, + onShowFunc?: (event: INotificationEvent) => void, + onCloseFunc?: (event: ICloseNotificationEvent) => void + } /** Change some config options. Can be run multiple times, also between notify()-calls to change electron-notifys behaviour. */ - export function setConfig(customConfig: ElectronNotify.IConfiguration): void; + export function setConfig(customConfig: ICustomConfig): void; /** Displays new notification. */ - export function notify(notification: ElectronNotify.INotification): void; + export function notify(notification: INotification): void; /** Clears the animation queue and closes all windows opened by electron-notify. Call this to clean up before quiting your app. */ export function closeAll(): void; From a1b6081ba37e8bb42d8ed51d07a281597b177b5f Mon Sep 17 00:00:00 2001 From: rchaser53 Date: Wed, 17 Aug 2016 00:30:11 +0900 Subject: [PATCH 078/564] add arguments type for using stateless functional component I added the type for DragSource arguments. But I forgot to add the other function arguments type. --- react-dnd/react-dnd.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/react-dnd/react-dnd.d.ts b/react-dnd/react-dnd.d.ts index 71b6adb51b..000cd04ee2 100644 --- a/react-dnd/react-dnd.d.ts +++ b/react-dnd/react-dnd.d.ts @@ -47,16 +47,16 @@ declare module __ReactDnd { spec: DropTargetSpec

    , collect: DropTargetCollector, options?: DndOptions

    - ): (componentClass: React.ComponentClass

    ) => DndComponentClass

    ; + ): (componentClass: React.ComponentClass

    | React.StatelessComponent

    ) => DndComponentClass

    ; export function DragDropContext

    ( backend: Backend - ): (componentClass: React.ComponentClass

    ) => ContextComponentClass

    ; + ):

    (componentClass: React.ComponentClass

    | React.StatelessComponent

    ) => ContextComponentClass

    ; export function DragLayer

    ( collect: DragLayerCollector, options?: DndOptions

    - ): (componentClass: React.ComponentClass

    ) => DndComponentClass

    ; + ): (componentClass: React.ComponentClass

    | React.StatelessComponent

    ) => DndComponentClass

    ; type DragSourceCollector = (connect: DragSourceConnector, monitor: DragSourceMonitor) => Object; type DropTargetCollector = (connect: DropTargetConnector, monitor: DropTargetMonitor) => Object; From e75095f1fdf63af6b1576b7aa0ec49f8f5963b1a Mon Sep 17 00:00:00 2001 From: David Poetzsch-Heffter Date: Tue, 16 Aug 2016 19:02:50 +0200 Subject: [PATCH 079/564] made sessionToken option available for all db operations (needed for cloud code in self-hosted parse-server) --- parse/parse.d.ts | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/parse/parse.d.ts b/parse/parse.d.ts index 6cf51a98b4..3a7d6b25f8 100644 --- a/parse/parse.d.ts +++ b/parse/parse.d.ts @@ -45,6 +45,9 @@ declare namespace Parse { useMasterKey?: boolean; } + interface ScopeOptions extends SessionTokenOption, UseMasterKeyOption { + } + interface SilentOption { /** * Set to true to avoid firing the event. @@ -363,15 +366,15 @@ declare namespace Parse { } namespace Object { - interface DestroyOptions extends SuccessFailureOptions, WaitOption, UseMasterKeyOption { } + interface DestroyOptions extends SuccessFailureOptions, WaitOption, ScopeOptions { } - interface DestroyAllOptions extends SuccessFailureOptions, UseMasterKeyOption { } + interface DestroyAllOptions extends SuccessFailureOptions, ScopeOptions { } - interface FetchOptions extends SuccessFailureOptions, UseMasterKeyOption { } + interface FetchOptions extends SuccessFailureOptions, ScopeOptions { } - interface SaveOptions extends SuccessFailureOptions, SilentOption, UseMasterKeyOption, WaitOption { } + interface SaveOptions extends SuccessFailureOptions, SilentOption, ScopeOptions, WaitOption { } - interface SaveAllOptions extends SuccessFailureOptions, UseMasterKeyOption { } + interface SaveAllOptions extends SuccessFailureOptions, ScopeOptions { } interface SetOptions extends ErrorOption, SilentOption { promise?: any; @@ -462,10 +465,10 @@ declare namespace Parse { at?: number; } - interface CreateOptions extends SuccessFailureOptions, WaitOption, SilentOption, UseMasterKeyOption { + interface CreateOptions extends SuccessFailureOptions, WaitOption, SilentOption, ScopeOptions { } - interface FetchOptions extends SuccessFailureOptions, SilentOption, UseMasterKeyOption { } + interface FetchOptions extends SuccessFailureOptions, SilentOption, ScopeOptions { } interface RemoveOptions extends SilentOption { } @@ -623,11 +626,11 @@ declare namespace Parse { } namespace Query { - interface EachOptions extends SuccessFailureOptions, UseMasterKeyOption { } - interface CountOptions extends SuccessFailureOptions, UseMasterKeyOption { } - interface FindOptions extends SuccessFailureOptions, UseMasterKeyOption { } - interface FirstOptions extends SuccessFailureOptions, UseMasterKeyOption { } - interface GetOptions extends SuccessFailureOptions, UseMasterKeyOption { } + interface EachOptions extends SuccessFailureOptions, ScopeOptions { } + interface CountOptions extends SuccessFailureOptions, ScopeOptions { } + interface FindOptions extends SuccessFailureOptions, ScopeOptions { } + interface FirstOptions extends SuccessFailureOptions, ScopeOptions { } + interface GetOptions extends SuccessFailureOptions, ScopeOptions { } } /** @@ -893,7 +896,7 @@ declare namespace Parse { function run(name: string, data?: any, options?: RunOptions): Promise; function useMasterKey(): void; - interface RunOptions extends SuccessFailureOptions, UseMasterKeyOption, SessionTokenOption { } + interface RunOptions extends SuccessFailureOptions, ScopeOptions { } /** * To use this Cloud Module in Cloud Code, you must require 'buffer' in your JavaScript file. From b8e87fd5302d9b7df7ef4498b64e1fd5961aea2e Mon Sep 17 00:00:00 2001 From: Leo Liang Date: Wed, 17 Aug 2016 01:35:43 +0800 Subject: [PATCH 080/564] node.d.ts : dgram : Allow option parameters to be omitted. --- node/node-tests.ts | 3 +++ node/node.d.ts | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index 32bdc94fdb..50242e9c31 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -507,9 +507,12 @@ namespace tty_tests { var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { }); +ds.bind(); +ds.bind(41234); var ai: dgram.AddressInfo = ds.address(); ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { }); +ds.send(new Buffer("hello"), 5000, "127.0.0.1"); //////////////////////////////////////////////////// ///Querystring tests : https://nodejs.org/api/querystring.html diff --git a/node/node.d.ts b/node/node.d.ts index 99963bf49e..61d98fb1ee 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1371,7 +1371,8 @@ declare module "dgram" { interface Socket extends events.EventEmitter { send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - bind(port: number, address?: string, callback?: () => void): void; + send(buf: Buffer, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port?: number, address?: string, callback?: () => void): void; close(): void; address(): AddressInfo; setBroadcast(flag: boolean): void; From 190beb00269d2a34ae7c60eab75c15690caef4b1 Mon Sep 17 00:00:00 2001 From: Andrew Connell Date: Tue, 16 Aug 2016 15:57:28 -0400 Subject: [PATCH 081/564] update wallabyjs.d.ts - richer typing Added better support for custom compilers, built in compilers and typing for the wallaby object passed in. --- wallabyjs/wallabyjs-tests.ts | 4 +-- wallabyjs/wallabyjs.d.ts | 54 ++++++++++++++++++++++++++++++++---- 2 files changed, 51 insertions(+), 7 deletions(-) diff --git a/wallabyjs/wallabyjs-tests.ts b/wallabyjs/wallabyjs-tests.ts index 832a775cd0..132984d039 100644 --- a/wallabyjs/wallabyjs-tests.ts +++ b/wallabyjs/wallabyjs-tests.ts @@ -13,7 +13,7 @@ export class WallabyConfig implements wallabyjs.IWallabyConfig { 'src/**/*.spec.ts' ]; - public compilers: wallabyjs.IWallabyCompiler = { + public compilers: wallabyjs.IWallabyCompilers = { 'src/**/*.js': this.wallaby.compilers.babel({}), 'src/**/*.ts': this.wallaby.compilers.typeScript({}) }; @@ -36,5 +36,5 @@ export class WallabyConfig implements wallabyjs.IWallabyConfig { } }; - constructor(private wallaby: any) { } + constructor(private wallaby: wallabyjs.IWallaby) { } } diff --git a/wallabyjs/wallabyjs.d.ts b/wallabyjs/wallabyjs.d.ts index 4f90762c2b..211963c8b3 100644 --- a/wallabyjs/wallabyjs.d.ts +++ b/wallabyjs/wallabyjs.d.ts @@ -24,7 +24,7 @@ declare module 'wallabyjs' { * @see {@link https://wallabyjs.com/docs/config/overview.html} for details. */ export interface IWallabyConfig { - comilers?: IWallabyCompiler; + comilers?: IWallabyCompilers; debug?: boolean; env?: IWallabyEnvironment; files: string[] | IWallabyFilePattern[]; @@ -36,16 +36,60 @@ declare module 'wallabyjs' { } /** - * Wallaby compiler configuration. + * Wallaby compilers. * + * @export * @interface IWallabyCompiler * * @see {@link https://wallabyjs.com/docs/config/compilers.html} for details. */ - export interface IWallabyCompiler { + export interface IWallabyCompilers { [pattern: string]: any } + /** + * Wallaby built in compiler options. These are name-value pairs passed into each compiler. + * + * @export + * @interface IWallabyCompilerOptions + * + * @see {@link https://wallabyjs.com/docs/config/compilers.html} for details. + */ + export interface IWallabyBuiltInCompilerOptions { + [option: string]: string; + } + + /** + * Wallaby build in compilers. + * + * @export + * @interface IWallabyBuiltInCompilers + * + * @see {@link https://wallabyjs.com/docs/config/compilers.html} for details. + */ + export interface IWallabyBuiltInCompilers { + babel(compilerOptions?: IWallabyBuiltInCompilerOptions): IWallabyCompilerResult; + coffeeScript(compilerOptions?: IWallabyBuiltInCompilerOptions): IWallabyCompilerResult; + typeScript(compilerOptions?: IWallabyBuiltInCompilerOptions): IWallabyCompilerResult; + } + + /** + * Wallaby compiler result entity. + * + * @export + * @interface IWallabyCompilerResult + * + * @property {string} map - Source map. + * @property {string} code - Code transformed to JavaScript. + * @property {any} ranges - All converable ranges of the original file. + * + * @see {@link https://wallabyjs.com/docs/config/compilers.html} for details. + */ + export interface IWallabyCompilerResult { + map: string; + code: string; + ranges: any; + } /** * Wallaby processor used in pre & post processors. @@ -149,7 +193,7 @@ declare module 'wallabyjs' { * * @property {string=} localProjectDir - String property which returns the project local folder. * @property {string=} projectCacheDir - String property which returns the project cache folder. - * @property {IWallabyCompiler=} compilers - Property which allows you to access the built-in TypeScript, CoffeeScript and Babel compilers. + * @property {IWallabyBuiltInCompilers=} compilers - Property which allows you to access the built-in TypeScript, CoffeeScript and Babel compilers. * @property {object=} defaults - Property which allows you to set the default values for file object properties. * * @see {@link https://wallabyjs.com/docs/config/overview.html} for details. @@ -157,7 +201,7 @@ declare module 'wallabyjs' { export interface IWallaby { localProjectDir?: string; projectCacheDir?: string; - compilers?: IWallabyCompiler; + compilers?: IWallabyBuiltInCompilers; defaults?: any; } } From b7802eae32129e2ca63bee58eec8df50fa691153 Mon Sep 17 00:00:00 2001 From: Seth Westphal Date: Tue, 16 Aug 2016 14:38:37 -0500 Subject: [PATCH 082/564] Add redis-scripto typings with tests. --- redis-scripto/redis-scripto-tests.ts | 37 ++++++++++++++++++++++++++ redis-scripto/redis-scripto.d.ts | 39 ++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 redis-scripto/redis-scripto-tests.ts create mode 100644 redis-scripto/redis-scripto.d.ts diff --git a/redis-scripto/redis-scripto-tests.ts b/redis-scripto/redis-scripto-tests.ts new file mode 100644 index 0000000000..235ebeb819 --- /dev/null +++ b/redis-scripto/redis-scripto-tests.ts @@ -0,0 +1,37 @@ +/// +/// + +import * as redis from 'redis'; +import * as Scripto from 'redis-scripto'; + +var num: number; +var str: string; +var options: redis.ClientOpts; +var redisClient = redis.createClient(num, str, options); + +var scriptManager = new Scripto(redisClient); +scriptManager.loadFromDir('/path/to/lua/scripts'); + +var keys = ['keyOne', 'keyTwo']; +var values = [10, 20]; +scriptManager.run('your-script', keys, values, function(err, result) { + +}); + +scriptManager.eval('your-script', keys, values, function(err, result) { + +}); + +scriptManager.loadFromFile('script-one', '/path/to/the/file'); +scriptManager.run('script-one', [], [], function(err, result) { + +}); + +var scripts: Scripto.Scripts = { + 'script-two': 'return 1000' +}; + +scriptManager.load(scripts); +scriptManager.run('script-two', [], [], function(err, result) { + +}); diff --git a/redis-scripto/redis-scripto.d.ts b/redis-scripto/redis-scripto.d.ts new file mode 100644 index 0000000000..e62e239210 --- /dev/null +++ b/redis-scripto/redis-scripto.d.ts @@ -0,0 +1,39 @@ +// Type definitions for redis-scripto 0.1.3 +// Project: https://github.com/arunoda/node-redis-scripto +// Definitions by: Seth Westphal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "redis-scripto" { + + import * as redis from 'redis'; + + class Scripto { + + constructor(redisClient: redis.RedisClient); + + eval(scriptName: string, keys: string[], args: any[], callback: (err: Error, result: any) => void): void; + evalSha(scriptName: string, keys: string[], args: any[], callback: (err: Error, result: any) => void): void; + + load(scripts: Scripto.Scripts): void; + loadFromDir(scriptsDir: string): void; + loadFromFile(name: string, filepath: string): void; + + run(scriptName: string, keys: string[], args: any[], callback: (err: Error, result: any) => void): void; + + } + + namespace Scripto { + + export type Script = string; + + export interface Scripts { + [scriptName: string]: Script; + } + + } + + export = Scripto; + +} From be6fac9f8ce56d7975c5ece31a144e96848fa33a Mon Sep 17 00:00:00 2001 From: Seth Westphal Date: Tue, 16 Aug 2016 15:55:10 -0500 Subject: [PATCH 083/564] Add redis-rate-limiter and tests. --- .../redis-rate-limiter-tests.ts | 41 +++++++++++++++++ redis-rate-limiter/redis-rate-limiter.d.ts | 44 +++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 redis-rate-limiter/redis-rate-limiter-tests.ts create mode 100644 redis-rate-limiter/redis-rate-limiter.d.ts diff --git a/redis-rate-limiter/redis-rate-limiter-tests.ts b/redis-rate-limiter/redis-rate-limiter-tests.ts new file mode 100644 index 0000000000..8fb68941ac --- /dev/null +++ b/redis-rate-limiter/redis-rate-limiter-tests.ts @@ -0,0 +1,41 @@ +/// +/// +/// + +import * as express from 'express'; +import * as redis from 'redis'; +import * as rateLimiter from 'redis-rate-limiter'; + +var num: number; +var str: string; +var options: redis.ClientOpts; +var redisClient = redis.createClient(num, str, options); + +var limit = rateLimiter.create({ + redis: redisClient, + key: function(x) { return x.ip }, + rate: '100/minute' +}); + +var request = {} as express.Request; +limit(request, function(err, rate) { + if (err) { + console.warn('Rate limiting not available'); + } else { + console.log('Rate window: ' + rate.window); // 60 + console.log('Rate limit: ' + rate.limit); // 100 + console.log('Rate current: ' + rate.current); // 74 + if (rate.over) { + console.error('Over the limit!'); + } + } +}); + +var middleware = rateLimiter.middleware({ + redis: redisClient, + key: 'ip', + rate: '100/minute' +}); + +var app = express(); +app.use(middleware); diff --git a/redis-rate-limiter/redis-rate-limiter.d.ts b/redis-rate-limiter/redis-rate-limiter.d.ts new file mode 100644 index 0000000000..6fa9998a0a --- /dev/null +++ b/redis-rate-limiter/redis-rate-limiter.d.ts @@ -0,0 +1,44 @@ +// Type definitions for redis-rate-limiter 1.0.3 +// Project: https://github.com/TabDigital/redis-rate-limiter +// Definitions by: Seth Westphal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module "redis-rate-limiter" { + + import * as express from 'express'; + import * as redis from 'redis'; + + class RedisRateLimiter { + + public static create(options: RedisRateLimiter.Options): + (req: express.Request, callback: (err: Error, res: RedisRateLimiter.Response) => void) => void; + public static middleware(options: RedisRateLimiter.Options): express.RequestHandler; + + } + + namespace RedisRateLimiter { + + export interface Options { + redis: redis.RedisClient; + key: 'ip' | ((req: express.Request) => string); + window?: number; + limit?: number; + rate?: string; + } + + export interface Response { + key: string; + current: number; + limit: number; + window: number; + over: boolean; + } + + } + + export = RedisRateLimiter; + +} From ad2267039b655754ecd546dd7414abe3787538df Mon Sep 17 00:00:00 2001 From: Seth Westphal Date: Tue, 16 Aug 2016 17:51:14 -0500 Subject: [PATCH 084/564] Rename auth0 -> auth0-js. --- auth0/auth0-tests.ts => auth0-js/auth0-js-tests.ts | 2 +- auth0/auth0.d.ts => auth0-js/auth0-js.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename auth0/auth0-tests.ts => auth0-js/auth0-js-tests.ts (91%) rename auth0/auth0.d.ts => auth0-js/auth0-js.d.ts (98%) diff --git a/auth0/auth0-tests.ts b/auth0-js/auth0-js-tests.ts similarity index 91% rename from auth0/auth0-tests.ts rename to auth0-js/auth0-js-tests.ts index 9cd903b306..c92251db91 100644 --- a/auth0/auth0-tests.ts +++ b/auth0-js/auth0-js-tests.ts @@ -1,4 +1,4 @@ -/// +/// var auth0 = new Auth0({ domain: 'mine.auth0.com', diff --git a/auth0/auth0.d.ts b/auth0-js/auth0-js.d.ts similarity index 98% rename from auth0/auth0.d.ts rename to auth0-js/auth0-js.d.ts index 5ca8487f85..1ee4ab9d7c 100644 --- a/auth0/auth0.d.ts +++ b/auth0-js/auth0-js.d.ts @@ -1,5 +1,5 @@ // Type definitions for Auth0.js -// Project: http://auth0.com +// Project: https://github.com/auth0/auth0.js // Definitions by: Robert McLaws // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From f471b0f7d78f0401773299e3f0634619e211b115 Mon Sep 17 00:00:00 2001 From: Seth Westphal Date: Tue, 16 Aug 2016 19:24:53 -0500 Subject: [PATCH 085/564] Fix auth0 -> auth0-js imports. --- auth0.lock/auth0.lock-tests.ts | 2 +- auth0.lock/auth0.lock.d.ts | 2 +- auth0.widget/auth0.widget-tests.ts | 2 +- auth0.widget/auth0.widget.d.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/auth0.lock/auth0.lock-tests.ts b/auth0.lock/auth0.lock-tests.ts index 07a7cf8323..d466cf5937 100644 --- a/auth0.lock/auth0.lock-tests.ts +++ b/auth0.lock/auth0.lock-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID"; diff --git a/auth0.lock/auth0.lock.d.ts b/auth0.lock/auth0.lock.d.ts index 7a459afd97..43d842aecc 100644 --- a/auth0.lock/auth0.lock.d.ts +++ b/auth0.lock/auth0.lock.d.ts @@ -3,7 +3,7 @@ // Definitions by: Brian Caruso // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0LockAdditionalSignUpFieldOption { value: string; diff --git a/auth0.widget/auth0.widget-tests.ts b/auth0.widget/auth0.widget-tests.ts index 012e9b9769..f44601986e 100644 --- a/auth0.widget/auth0.widget-tests.ts +++ b/auth0.widget/auth0.widget-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// var widget: Auth0WidgetStatic = new Auth0Widget({ diff --git a/auth0.widget/auth0.widget.d.ts b/auth0.widget/auth0.widget.d.ts index 20694526c3..e36a7f868a 100644 --- a/auth0.widget/auth0.widget.d.ts +++ b/auth0.widget/auth0.widget.d.ts @@ -3,7 +3,7 @@ // Definitions by: Robert McLaws // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0WidgetStatic { From 0fdba28d3871b1e649567b1f41c2d053a358bdbd Mon Sep 17 00:00:00 2001 From: Seth Westphal Date: Tue, 16 Aug 2016 19:46:02 -0500 Subject: [PATCH 086/564] Add auth0 typings and tests. --- auth0/auth0-tests.ts | 51 ++++++++++++++++++++++++ auth0/auth0.d.ts | 95 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 146 insertions(+) create mode 100644 auth0/auth0-tests.ts create mode 100644 auth0/auth0.d.ts diff --git a/auth0/auth0-tests.ts b/auth0/auth0-tests.ts new file mode 100644 index 0000000000..a1357246f3 --- /dev/null +++ b/auth0/auth0-tests.ts @@ -0,0 +1,51 @@ +/// + +import * as auth0 from 'auth0'; + +const management = new auth0.ManagementClient({ + token: '{YOUR_API_V2_TOKEN}', + domain: '{YOUR_ACCOUNT}.auth0.com' +}); + +const auth = new auth0.AuthenticationClient({ + domain: '{YOUR_ACCOUNT}.auth0.com', + clientId: '{OPTIONAL_CLIENT_ID}' +}); + +// Using a callback. +management.getUsers((err: Error, users: auth0.User[]) => { + if (err) { + // Handle error. + } + console.log(users); +}); + +// Using a Promise. +management + .getUsers() + .then((users) => { + console.log(users); + }) + .catch((err) => { + // Handle the error. + }); + +management + .createUser({ + connection: 'My-Connection', + email: 'hi@me.co', + }).then((user) => { + console.log(user); + }).catch((err) => { + // Handle the error. + }); + +auth + .requestChangePasswordEmail({ + connection: 'My-Connection', + email: 'hi@me.co', + }).then((response) => { + console.log(response); + }).catch((err) => { + // Handle the error. + }); diff --git a/auth0/auth0.d.ts b/auth0/auth0.d.ts new file mode 100644 index 0000000000..e367d30411 --- /dev/null +++ b/auth0/auth0.d.ts @@ -0,0 +1,95 @@ +// Type definitions for auth0 v2.3.1 +// Project: https://github.com/auth0/node-auth0 +// Definitions by: Seth Westphal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "auth0" { + + import * as Promise from 'bluebird'; + + export interface ManagementClientOptions { + token: string; + domain?: string; + } + + export interface UserData { + connection: string; + email?: string; + username?: string; + password?: string; + phone_number?: string; + user_metadata?: {}; + email_verified?: boolean; + app_metadata?: {}; + } + + export interface GetUsersData { + per_page?: number; + page?: number; + include_totals?: boolean; + sort?: string; + connection?: string; + fields?: string; + include_fields?: boolean; + q?: string; + search_engine?: string; + } + + export interface User { + email?: string; + email_verified?: boolean; + username?: string; + phone_number?: string; + phone_verified?: boolean; + user_id?: string; + created_at?: string; + updated_at?: string; + identities?: Identity[]; + app_metadata?: {}; + user_metadata?: {}; + picture?: string; + name?: string; + nickname?: string; + multifactor?: string[]; + last_ip?: string; + last_login?: string; + logins_count?: number; + blocked?: boolean; + } + + export interface Identity { + connection: string; + user_id: string; + provider: string; + isSocial: boolean; + } + + export class ManagementClient { + constructor(options: ManagementClientOptions); + + getUsers(params?: GetUsersData): Promise; + getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void; + createUser(data: UserData): Promise; + createUser(data: UserData, cb: (err: Error, data: User) => void): void; + } + + export interface AuthenticationClientOptions { + clientId?: string; + domain: string; + } + + export interface RequestChangePasswordEmailData { + connection: string; + email: string; + } + + export class AuthenticationClient { + constructor(options: AuthenticationClientOptions); + + requestChangePasswordEmail(data: RequestChangePasswordEmailData): Promise; + requestChangePasswordEmail(data: RequestChangePasswordEmailData, cb: (err: Error, message: string) => void): void; + } + +} From d887ba6c3cb656316d96d06a5499910358963c20 Mon Sep 17 00:00:00 2001 From: rhysd Date: Wed, 17 Aug 2016 15:16:22 +0900 Subject: [PATCH 087/564] electron-prebuilt was renamed to electron http://electron.atom.io/blog/2016/08/16/npm-install-electron --- .../{electron-prebuilt-tests.ts => electron-tests.ts} | 4 ++-- github-electron/{electron-prebuilt.d.ts => electron.d.ts} | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) rename github-electron/{electron-prebuilt-tests.ts => electron-tests.ts} (56%) rename github-electron/{electron-prebuilt.d.ts => electron.d.ts} (53%) diff --git a/github-electron/electron-prebuilt-tests.ts b/github-electron/electron-tests.ts similarity index 56% rename from github-electron/electron-prebuilt-tests.ts rename to github-electron/electron-tests.ts index 771fd06016..00b34d60b1 100644 --- a/github-electron/electron-prebuilt-tests.ts +++ b/github-electron/electron-tests.ts @@ -1,7 +1,7 @@ -/// +/// /// -import electron = require('electron-prebuilt'); +import electron = require('electron'); import child_process = require('child_process'); child_process.spawn(electron); diff --git a/github-electron/electron-prebuilt.d.ts b/github-electron/electron.d.ts similarity index 53% rename from github-electron/electron-prebuilt.d.ts rename to github-electron/electron.d.ts index d6b6dffc0e..5e331b3e47 100644 --- a/github-electron/electron-prebuilt.d.ts +++ b/github-electron/electron.d.ts @@ -1,9 +1,9 @@ -// Type definitions for electron-prebuilt 0.30.1 -// Project: https://github.com/mafintosh/electron-prebuilt +// Type definitions for electron 1.3.3 +// Project: https://github.com/electron-userland/electron-prebuilt // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'electron-prebuilt' { +declare module 'electron' { var electron: string; export = electron; } From f1c88a8096d9892bec602a4bb1f560d33d0c82c7 Mon Sep 17 00:00:00 2001 From: Maxim Samoilov Date: Tue, 16 Aug 2016 14:40:01 +0700 Subject: [PATCH 088/564] test(react): add strictNullChecks test #10421 --- react/react-tsx-tests.tsx | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 react/react-tsx-tests.tsx diff --git a/react/react-tsx-tests.tsx b/react/react-tsx-tests.tsx new file mode 100644 index 0000000000..303a6b1f42 --- /dev/null +++ b/react/react-tsx-tests.tsx @@ -0,0 +1,16 @@ +/// +import React = require("react"); + +interface SCProps { + foo?: number; +} + +var StatelessComponent: React.SFC = ({ foo }: SCProps) => { + return

    { foo }
    ; +}; +StatelessComponent.displayName = "StatelessComponent3"; +StatelessComponent.defaultProps = { + foo: 42 +}; + +; From d72a787f0dfc80d3320842697d23f122644533ab Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Wed, 17 Aug 2016 10:06:23 +0300 Subject: [PATCH 089/564] Update react.d.ts --- react/react.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react/react.d.ts b/react/react.d.ts index f3ce283545..7f3c87082a 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -276,10 +276,10 @@ declare namespace __React { isTrusted: boolean; nativeEvent: Event; preventDefault(): void; - stopPropagation(): void; - persist(): void; isDefaultPrevented(): boolean; + stopPropagation(): void; isPropagationStopped(): boolean; + persist(): void; target: EventTarget; timeStamp: Date; type: string; From 5073eb65dc9d6617d67d2c7b0a11e25d3b9ca6cb Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 17 Aug 2016 17:07:40 +0800 Subject: [PATCH 090/564] http.IncomingMessage: destroy not found Please refer to https://nodejs.org/api/http.html#http_message_destroy_error --- node/node.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node/node.d.ts b/node/node.d.ts index 99963bf49e..8b944dda8d 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -670,6 +670,7 @@ declare module "http" { */ statusMessage?: string; socket: net.Socket; + destroy(error: Error): void; } /** * @deprecated Use IncomingMessage From 75bfef43c60910b770bbee513c019f055d16ab85 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 17 Aug 2016 17:36:04 +0800 Subject: [PATCH 091/564] destroy has a optional argument --- 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 8b944dda8d..3177d9d290 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -670,7 +670,7 @@ declare module "http" { */ statusMessage?: string; socket: net.Socket; - destroy(error: Error): void; + destroy(error?: Error): void; } /** * @deprecated Use IncomingMessage From ab22123c9c46173dda11d0d4d636fe336f492923 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 17 Aug 2016 17:36:56 +0800 Subject: [PATCH 092/564] destroy has a optional argument From 79dcf14a6ba1ae5fd1d2962916201fe45a48c98d Mon Sep 17 00:00:00 2001 From: Andrew Connell Date: Wed, 17 Aug 2016 06:16:16 -0400 Subject: [PATCH 093/564] update header with my GH link for DT-BOT --- wallabyjs/wallabyjs.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wallabyjs/wallabyjs.d.ts b/wallabyjs/wallabyjs.d.ts index 211963c8b3..7b791e44ff 100644 --- a/wallabyjs/wallabyjs.d.ts +++ b/wallabyjs/wallabyjs.d.ts @@ -1,6 +1,6 @@ // Type definitions for WallabyJS // Project: http://wallabyjs.com -// Definitions by: Andrew Connell +// Definitions by: Andrew Connell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'wallabyjs' { From 739bd1a4746ed933a388321bcd02975c11c3430a Mon Sep 17 00:00:00 2001 From: york yao Date: Wed, 17 Aug 2016 18:54:40 +0800 Subject: [PATCH 094/564] the muster.array() 's parameter is optional --- multer/multer.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/multer/multer.d.ts b/multer/multer.d.ts index 4b70555af8..2a4eea805f 100644 --- a/multer/multer.d.ts +++ b/multer/multer.d.ts @@ -90,7 +90,7 @@ declare module "multer" { /** Accept a single file with the name fieldname. The single file will be stored in req.file. */ single(fieldame: string): express.RequestHandler; /** Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files. */ - array(fieldame: string, maxCount?: number): express.RequestHandler; + array(fieldame?: string, maxCount?: number): express.RequestHandler; /** Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files. */ fields(fields: Field[]): express.RequestHandler; /** Accepts all files that comes over the wire. An array of files will be stored in req.files. */ From 8039434c204a56b575f56fa2860654da808db208 Mon Sep 17 00:00:00 2001 From: Nicholas Iannone Date: Wed, 17 Aug 2016 09:53:59 -0500 Subject: [PATCH 095/564] Renamed modules. --- db-migrate-base/db-migrate-base-tests.ts | 2 +- db-migrate-base/db-migrate-base.d.ts | 2 +- db-migrate-pg/db-migrate-pg-tests.ts | 2 +- db-migrate-pg/db-migrate-pg.d.ts | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/db-migrate-base/db-migrate-base-tests.ts b/db-migrate-base/db-migrate-base-tests.ts index 68c61e6f6c..55d471b98f 100644 --- a/db-migrate-base/db-migrate-base-tests.ts +++ b/db-migrate-base/db-migrate-base-tests.ts @@ -1,7 +1,7 @@ // Test file for db-migrate-base Definition file /// -import * as DbMigrateBase from "DbMigrateBase"; +import * as DbMigrateBase from "db-migrate-base"; // Throw together a dummy driver let db = {}; diff --git a/db-migrate-base/db-migrate-base.d.ts b/db-migrate-base/db-migrate-base.d.ts index 47dd8ce1c2..fe1f4ade47 100644 --- a/db-migrate-base/db-migrate-base.d.ts +++ b/db-migrate-base/db-migrate-base.d.ts @@ -6,7 +6,7 @@ /// /// -declare module "DbMigrateBase" { +declare module "db-migrate-base" { export interface CallbackFunction { (err: any, response: any): void; } diff --git a/db-migrate-pg/db-migrate-pg-tests.ts b/db-migrate-pg/db-migrate-pg-tests.ts index ad2430440c..3878c54607 100644 --- a/db-migrate-pg/db-migrate-pg-tests.ts +++ b/db-migrate-pg/db-migrate-pg-tests.ts @@ -1,7 +1,7 @@ // Test file for db-migrate-pg Definition file /// -import * as DbMigratePg from "DbMigratePg"; +import * as DbMigratePg from "db-migrate-pg"; // Throw together a dummy driver let db = {}; diff --git a/db-migrate-pg/db-migrate-pg.d.ts b/db-migrate-pg/db-migrate-pg.d.ts index 4d2823ec52..aa1a52d34e 100644 --- a/db-migrate-pg/db-migrate-pg.d.ts +++ b/db-migrate-pg/db-migrate-pg.d.ts @@ -6,10 +6,10 @@ /// /// -declare module "DbMigratePg" { +declare module "db-migrate-pg" { import * as pg from "pg"; - import * as DbMigrateBase from "DbMigrateBase"; + import * as DbMigrateBase from "db-migrate-base"; // Yes, this is a dummy interface for now; the current implementation of the pg driver doesn't need any options. export interface CreateDatabaseOptions {} From 45f675a1624a24ef5bf20ec74bf7e90c3e56629e Mon Sep 17 00:00:00 2001 From: Ilia Choly Date: Wed, 17 Aug 2016 11:06:04 -0400 Subject: [PATCH 096/564] 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 896f3172983d25c405be5ad21f3cc20f136ae0ee Mon Sep 17 00:00:00 2001 From: Luke Street Date: Wed, 17 Aug 2016 11:56:21 -0400 Subject: [PATCH 097/564] lodash: Added flush method to debounced & throttled functions --- lodash/lodash.d.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 52f274fd3c..e64c868354 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -172,6 +172,7 @@ Other changes - [x] Ensured _.range preserves the sign of start of -0 - [x] Ensured _.reduce & _.reduceRight use getIteratee in their array branch - [x] Fixed rounding issue with the precision param of _.floor +- [x] Added flush method to debounced & throttled functions ** LATER ** Misc: @@ -185,7 +186,6 @@ Misc: - [ ] _.extend as an alias of _.assignIn - [ ] _.extendWith as an alias of _.assignInWith - [ ] Added clear method to _.memoize.Cache -- [ ] Added flush method to debounced & throttled functions - [ ] Added support for ES6 maps, sets, & symbols to _.clone, _.isEqual, & _.toArray - [ ] Enabled _.flow & _.flowRight to accept an array of functions - [ ] Ensured “Collection” methods treat functions as objects @@ -10132,9 +10132,9 @@ declare module _ { /** * Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since * the last time the debounced function was invoked. The debounced function comes with a cancel method to - * cancel delayed invocations. Provide an options object to indicate that func should be invoked on the - * leading and/or trailing edge of the wait timeout. Subsequent calls to the debounced function return the - * result of the last func invocation. + * cancel delayed invocations and a flush method to immediately invoke them. Provide an options object to + * indicate that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent + * calls to the debounced function return the result of the last func invocation. * * Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only * if the the debounced function is invoked more than once during the wait timeout. @@ -10755,9 +10755,9 @@ declare module _ { interface LoDashStatic { /** * Creates a throttled function that only invokes func at most once per every wait milliseconds. The throttled - * function comes with a cancel method to cancel delayed invocations. Provide an options object to indicate - * that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls to - * the throttled function return the result of the last func call. + * function comes with a cancel method to cancel delayed invocations and a flush method to immediately invoke + * them. Provide an options object to indicate that func should be invoked on the leading and/or trailing edge + * of the wait timeout. Subsequent calls to the throttled function return the result of the last func call. * * Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if * the the throttled function is invoked more than once during the wait timeout. @@ -19159,6 +19159,7 @@ declare module _ { interface Cancelable { cancel(): void; + flush(): void; } } From 383dc7a3a4fc24a3f1a1fdf17a6e051f1648f0e0 Mon Sep 17 00:00:00 2001 From: Ilia Choly Date: Wed, 17 Aug 2016 12:06:58 -0400 Subject: [PATCH 098/564] 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 099/564] 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 dcaf000f890831e3e8431f0f682c7fffd06241ee Mon Sep 17 00:00:00 2001 From: Marcel Haldemann Date: Wed, 17 Aug 2016 19:12:21 +0200 Subject: [PATCH 100/564] make express.Application compatible with http.createServer --- 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 de91c521cc..f83e509e63 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -22,7 +22,7 @@ declare module "express-serve-static-core" { } interface RequestHandler { - (req: Request, res: Response, next: NextFunction): any; + (req: Request, res: Response, next?: NextFunction): any; } interface ErrorRequestHandler { From 5953dd4f6c9cebee89f6f26da74280d525c21d08 Mon Sep 17 00:00:00 2001 From: Daryl LaBar Date: Wed, 17 Aug 2016 14:08:01 -0400 Subject: [PATCH 101/564] Verified that addPreSearch returns a ContextSensitiveHandler, and since the handler is added against a control, the getEventSource can return a Control as well.. --- xrm/xrm.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xrm/xrm.d.ts b/xrm/xrm.d.ts index cf2b4c77c3..824c91ba0c 100644 --- a/xrm/xrm.d.ts +++ b/xrm/xrm.d.ts @@ -786,7 +786,7 @@ declare namespace Xrm * * @return The event source. */ - getEventSource(): Attribute | Entity; + getEventSource(): Attribute | Control | Entity; /** * Gets the shared variable with the specified key. @@ -1726,7 +1726,7 @@ declare namespace Xrm * * @param {Function} handler The handler. */ - addPreSearch( handler: () => void ): void; + addPreSearch( handler: ContextSensitiveHandler ): void; /** * Adds an additional custom filter to the lookup, with the "AND" filter operator. From 40c950b9239ddfc16a3e4b45add90bc9b06f3647 Mon Sep 17 00:00:00 2001 From: Schmulik Raskin Date: Wed, 17 Aug 2016 23:43:33 +0300 Subject: [PATCH 102/564] Add namespace to gulp-rename to make export work --- gulp-rename/gulp-rename-tests.ts | 5 ++++- gulp-rename/gulp-rename.d.ts | 9 ++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/gulp-rename/gulp-rename-tests.ts b/gulp-rename/gulp-rename-tests.ts index 6b204a36d9..b27f0f5ba9 100644 --- a/gulp-rename/gulp-rename-tests.ts +++ b/gulp-rename/gulp-rename-tests.ts @@ -3,6 +3,9 @@ import gulp = require("gulp"); import rename = require("gulp-rename"); +// Test that new import syntax works +import * as newRename from 'gulp-rename'; + // rename via string gulp.src("./src/main/text/hello.txt") .pipe(rename("main/text/ciao/goodbye.md")) @@ -26,4 +29,4 @@ gulp.src("./src/main/text/hello.txt", { base: process.cwd() }) suffix: "-hola", extname: ".md" })) - .pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/bonjour-aloha-hola.md \ No newline at end of file + .pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/bonjour-aloha-hola.md diff --git a/gulp-rename/gulp-rename.d.ts b/gulp-rename/gulp-rename.d.ts index 11368e9698..4c68aecde7 100644 --- a/gulp-rename/gulp-rename.d.ts +++ b/gulp-rename/gulp-rename.d.ts @@ -20,5 +20,12 @@ declare module "gulp-rename" { function rename(name: string): NodeJS.ReadWriteStream; function rename(callback: (path: ParsedPath) => any): NodeJS.ReadWriteStream; function rename(opts: Options): NodeJS.ReadWriteStream; + + /** + * This is required as per: + * https://github.com/Microsoft/TypeScript/issues/5073 + */ + namespace rename {} + export = rename; -} \ No newline at end of file +} From 4d42a7f7bda33685b99e633c6785bbaef6810e14 Mon Sep 17 00:00:00 2001 From: york yao Date: Thu, 18 Aug 2016 06:54:59 +0800 Subject: [PATCH 103/564] add override method of the multer methods (.single(), .array(), fields()) --- multer/multer.d.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/multer/multer.d.ts b/multer/multer.d.ts index 2a4eea805f..2ffaf61760 100644 --- a/multer/multer.d.ts +++ b/multer/multer.d.ts @@ -89,12 +89,18 @@ declare module "multer" { interface Instance { /** Accept a single file with the name fieldname. The single file will be stored in req.file. */ single(fieldame: string): express.RequestHandler; + /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ + single(): express.RequestHandler; /** Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files. */ - array(fieldame?: string, maxCount?: number): express.RequestHandler; + array(fieldame: string, maxCount?: number): express.RequestHandler; + /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ + array(): express.RequestHandler; /** Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files. */ fields(fields: Field[]): express.RequestHandler; /** Accepts all files that comes over the wire. An array of files will be stored in req.files. */ any(): express.RequestHandler; + /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ + any(): express.RequestHandler; } } From 3c322e8e4dfae92f16a191d9e9a0b528860c96e9 Mon Sep 17 00:00:00 2001 From: Stefan Valentin Date: Wed, 17 Aug 2016 19:19:09 -0500 Subject: [PATCH 104/564] eventemitter2: Namespaces allow string[] for on/emit --- eventemitter2/eventemitter2.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/eventemitter2/eventemitter2.d.ts b/eventemitter2/eventemitter2.d.ts index 39a349c6b6..de1be0d064 100644 --- a/eventemitter2/eventemitter2.d.ts +++ b/eventemitter2/eventemitter2.d.ts @@ -43,7 +43,7 @@ declare class EventEmitter2 { * @param event * @param listener */ - on(event: string, listener: Function): EventEmitter2; + on(event: string | string[], listener: Function): EventEmitter2; /** * Adds a listener that will be fired when any event is emitted. @@ -128,7 +128,7 @@ declare class EventEmitter2 { * @param event * @param args */ - emit(event: string, ...args: any[]): boolean; + emit(event: string | string[], ...args: any[]): boolean; /** * Execute each of the listeners that may be listening for the specified event name in order with the list of arguments. @@ -156,7 +156,7 @@ declare module "eventemitter2" { * @param event * @param listener */ - on(event: string, listener: Function): EventEmitter2; + on(event: string | string[], listener: Function): EventEmitter2; /** * Adds a listener that will be fired when any event is emitted. @@ -241,7 +241,7 @@ declare module "eventemitter2" { * @param event * @param args */ - emit(event: string, ...args: any[]): boolean; + emit(event: string | string[], ...args: any[]): boolean; /** * Execute each of the listeners that may be listening for the specified event name in order with the list of arguments. From b711ae75b8e05ffa4ce31981009bb1e59001ba92 Mon Sep 17 00:00:00 2001 From: bradley cushing Date: Wed, 17 Aug 2016 22:35:10 -0400 Subject: [PATCH 105/564] Update TabListProps interface with new optional props Changes were introduced in react-tabs PR #108. --- react-tabs/react-tabs.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/react-tabs/react-tabs.d.ts b/react-tabs/react-tabs.d.ts index 758db0d75c..565b055304 100644 --- a/react-tabs/react-tabs.d.ts +++ b/react-tabs/react-tabs.d.ts @@ -21,6 +21,8 @@ declare namespace ReactTabs { interface TabListProps { className?: string; + activeTabClassName?: string; + disabledTabClassName?: string; } interface TabList extends __React.ComponentClass {} From 5baa6e08ea662c63e73a820451f9e85ddc5d63bc Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 18 Aug 2016 11:34:00 +0800 Subject: [PATCH 106/564] express.Application is compatible with http.createServer Add test case: express.Application is compatible with http.createServer --- express/express-tests.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/express/express-tests.ts b/express/express-tests.ts index ed9265b66a..439ef95012 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -1,4 +1,5 @@ /// +/// import * as express from 'express'; var app = express(); @@ -91,3 +92,10 @@ app.listen(3000); const next: express.NextFunction = () => {}; const nextWithArgument: express.NextFunction = (err: any) => {}; + +/** + * The express.Application is compatible with http.createServer + */ + +import * as http from 'http'; +http.createServer(app); From 7d940e6e669eb3a267523b1995718f268044c2b0 Mon Sep 17 00:00:00 2001 From: Gayan Ranasinghe Date: Thu, 18 Aug 2016 10:44:23 +0530 Subject: [PATCH 107/564] fixes --- kendo-ui/kendo-ui.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index ab09a8882f..e8f02f1776 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -5,7 +5,6 @@ /// - declare namespace kendo { function culture(): { name: string; @@ -511,7 +510,7 @@ declare namespace kendo.data { render(value: Object): string; } - module binders { } + namespace binders { } interface Bindings { [key: string]: Binding; From 64ee4c96285cad9bf3e96d511c88849d654558a8 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 09:23:56 +0300 Subject: [PATCH 108/564] getInputNode should return HTMLInputElement --- material-ui/material-ui.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index 58a36f9cf9..6d48b46e58 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -1712,7 +1712,7 @@ declare namespace __MaterialUI { focus(): void; select(): void; getValue(): string; - getInputNode(): Element; + getInputNode(): HTMLInputElement; } interface TimePickerProps extends React.Props { From 4a97011cb6fd9a584510d569387527a49c70612d Mon Sep 17 00:00:00 2001 From: Lutz Rosema Date: Thu, 18 Aug 2016 10:35:05 +0200 Subject: [PATCH 109/564] 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 81742efd81d2d70b63636678f54e4e03af23d318 Mon Sep 17 00:00:00 2001 From: Finn Poppinga Date: Thu, 18 Aug 2016 13:00:30 +0200 Subject: [PATCH 110/564] add missing command HINCRBYFLOAT --- redis/redis.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/redis/redis.d.ts b/redis/redis.d.ts index de52145261..5c8fd6b39f 100644 --- a/redis/redis.d.ts +++ b/redis/redis.d.ts @@ -109,7 +109,7 @@ declare module "redis" { "lset", "lrange", "ltrim", "lrem", "rpoplpush", "sadd", "srem", "smove", "sismember", "scard", "spop", "srandmember", "sinter", "sinterstore", "sunion", "sunionstore", "sdiff", "sdiffstore", "smembers", "zadd", "zincrby", "zrem", "zremrangebyscore", "zremrangebyrank", "zunionstore", "zinterstore", "zrange", "zrangebyscore", "zrevrangebyscore", "zcount", "zrevrange", "zcard", "zscore", "zrank", "zrevrank", "hset", "hsetnx", - "hget", "hmset", "hmget", "hincrby", "hdel", "hlen", "hkeys", "hvals", "hgetall", "hexists", "incrby", "decrby", "getset", "mset", "msetnx", + "hget", "hmset", "hmget", "hincrby", "hincrbyfloat", "hdel", "hlen", "hkeys", "hvals", "hgetall", "hexists", "incrby", "decrby", "getset", "mset", "msetnx", "randomkey", "select", "move", "rename", "renamenx", "expire", "expireat", "keys", "dbsize", "auth", "ping", "echo", "save", "bgsave", "bgrewriteaof", "shutdown", "lastsave", "type", "multi", "exec", "discard", "sync", "flushdb", "flushall", "sort", "info", "monitor", "ttl", "persist", "slaveof", "debug", "config", "subscribe", "unsubscribe", "psubscribe", "punsubscribe", "publish", "watch", "unwatch", "cluster", @@ -254,6 +254,8 @@ declare module "redis" { hmget(...args:any[]): boolean; hincrby(args:any[], callback?:ResCallbackT): boolean; hincrby(...args:any[]): boolean; + hincrbyfloat(args:any[], callback?:ResCallbackT): boolean; + hincrbyfloat(...args:any[]): boolean; hdel(args:any[], callback?:ResCallbackT): boolean; hdel(...args:any[]): boolean; hlen(args:any[], callback?:ResCallbackT): boolean; From cb827241b88929adce8708fad4395452e4b76941 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 15:42:15 +0300 Subject: [PATCH 111/564] Create simple-assign.d.ts --- simple-assign/simple-assign.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 simple-assign/simple-assign.d.ts diff --git a/simple-assign/simple-assign.d.ts b/simple-assign/simple-assign.d.ts new file mode 100644 index 0000000000..594e0f98ef --- /dev/null +++ b/simple-assign/simple-assign.d.ts @@ -0,0 +1,8 @@ +// Type definitions for simple-assign 0.1.0 +// Project: https://github.com/sindresorhus/object-assign +// Definitions by: Ivo Stratev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "simple-assign" { + export defualt function(target: any, ...sources: any[]): any; +} From 50e30a81c79d885db610d9733bf0d05721cbadda Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 15:45:04 +0300 Subject: [PATCH 112/564] Create simple-assign-tests.d.ts --- simple-assign/simple-assign-tests.d.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 simple-assign/simple-assign-tests.d.ts diff --git a/simple-assign/simple-assign-tests.d.ts b/simple-assign/simple-assign-tests.d.ts new file mode 100644 index 0000000000..3b901540e4 --- /dev/null +++ b/simple-assign/simple-assign-tests.d.ts @@ -0,0 +1,15 @@ + +/// +import * as assign from "simple-assign"; + +function assign1() { + return assign({hello: "world"}); +} + +function assign2() { + return assign({hello: "world"}, {hello: "worlds", second: "extra"}); +} + +function assign3() { + return assign({hello: "world"}, {hello: "worlds", second: "extra"}, {hello: "stop", the: "spinning"}); +} From 224e661e5b10b072a72111b9871ad7da95aea6da Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 15:46:20 +0300 Subject: [PATCH 113/564] Update simple-assign.d.ts --- simple-assign/simple-assign.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/simple-assign/simple-assign.d.ts b/simple-assign/simple-assign.d.ts index 594e0f98ef..ee122703fa 100644 --- a/simple-assign/simple-assign.d.ts +++ b/simple-assign/simple-assign.d.ts @@ -1,5 +1,5 @@ // Type definitions for simple-assign 0.1.0 -// Project: https://github.com/sindresorhus/object-assign +// Project: https://github.com/newoga/simple-assign // Definitions by: Ivo Stratev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 7e8ee0b8ce9e28426dcd0485a7abcb3955fedbb9 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 15:52:44 +0300 Subject: [PATCH 114/564] Update simple-assign.d.ts --- simple-assign/simple-assign.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/simple-assign/simple-assign.d.ts b/simple-assign/simple-assign.d.ts index ee122703fa..f16d87fad5 100644 --- a/simple-assign/simple-assign.d.ts +++ b/simple-assign/simple-assign.d.ts @@ -4,5 +4,5 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "simple-assign" { - export defualt function(target: any, ...sources: any[]): any; + export default function(target: any, ...sources: any[]): any; } From aca9b1cd2895eeabf9152ffc58ddea2ec3ff6c47 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 15:52:54 +0300 Subject: [PATCH 115/564] Rename simple-assign-tests.d.ts to simple-assign-tests.ts --- .../{simple-assign-tests.d.ts => simple-assign-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename simple-assign/{simple-assign-tests.d.ts => simple-assign-tests.ts} (100%) diff --git a/simple-assign/simple-assign-tests.d.ts b/simple-assign/simple-assign-tests.ts similarity index 100% rename from simple-assign/simple-assign-tests.d.ts rename to simple-assign/simple-assign-tests.ts From 875b8b14b2ea73242eea76660c568e527abb9ba3 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 15:58:06 +0300 Subject: [PATCH 116/564] Update simple-assign-tests.ts --- simple-assign/simple-assign-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/simple-assign/simple-assign-tests.ts b/simple-assign/simple-assign-tests.ts index 3b901540e4..9afada70dd 100644 --- a/simple-assign/simple-assign-tests.ts +++ b/simple-assign/simple-assign-tests.ts @@ -1,6 +1,6 @@ /// -import * as assign from "simple-assign"; +import assign from "simple-assign"; function assign1() { return assign({hello: "world"}); From 648906b7c7de03a0032ed66d850582856ebef97e Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 16:16:29 +0300 Subject: [PATCH 117/564] Update simple-assign.d.ts --- simple-assign/simple-assign.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/simple-assign/simple-assign.d.ts b/simple-assign/simple-assign.d.ts index f16d87fad5..1c65a8e0f9 100644 --- a/simple-assign/simple-assign.d.ts +++ b/simple-assign/simple-assign.d.ts @@ -4,5 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "simple-assign" { - export default function(target: any, ...sources: any[]): any; + function simpleAssign(target: any, ...sources: any[]): any; + export = simpleAssign; } From 8fa7243389ed378b73fbac7f2b525d5cbd225412 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 16:16:56 +0300 Subject: [PATCH 118/564] Update simple-assign-tests.ts --- simple-assign/simple-assign-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/simple-assign/simple-assign-tests.ts b/simple-assign/simple-assign-tests.ts index 9afada70dd..3970356f5b 100644 --- a/simple-assign/simple-assign-tests.ts +++ b/simple-assign/simple-assign-tests.ts @@ -1,6 +1,6 @@ /// -import assign from "simple-assign"; +import assign = require("simple-assign"); function assign1() { return assign({hello: "world"}); From 718c73a6bb01fdc5f8a44aad0b90d5de741525e1 Mon Sep 17 00:00:00 2001 From: Daniel Pereira Date: Thu, 18 Aug 2016 09:50:21 -0500 Subject: [PATCH 119/564] Added mock-require --- mock-require/mock-require-tests.ts | 47 ++++++++++++++++++++++++++++++ mock-require/mock-require.d.ts | 35 ++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 mock-require/mock-require-tests.ts create mode 100644 mock-require/mock-require.d.ts diff --git a/mock-require/mock-require-tests.ts b/mock-require/mock-require-tests.ts new file mode 100644 index 0000000000..528d466064 --- /dev/null +++ b/mock-require/mock-require-tests.ts @@ -0,0 +1,47 @@ +/// + +import mock = require('mock-require'); + +function testMock() { + mock('http', { + request: function () { + console.log('http.request called'); + } + }); + + const http = require('http'); + http.request(); // 'http.request called' +} + +function testStop() { + mock('fs', { mockedFS: true }); + + const fs1 = require('fs'); + mock.stop('fs'); + + const fs2 = require('fs'); + fs1 === fs2; // false +} + +function testStopAll() { + mock('fs', {}); + mock('path', {}); + + const fs1 = require('fs'); + const path1 = require('path'); + + mock.stopAll(); + + const fs2 = require('fs'); + const path2 = require('path'); + + fs1 === fs2; // false + path1 === path2; // false +} + +function testReRequire() { + const fs = require('fs'); + let fileToTest = require('./fileToTest'); + mock('fs', {}); // fileToTest is still using the unmocked fs module + fileToTest = mock.reRequire('./fileToTest'); // fileToTest is now using your mock +} \ No newline at end of file diff --git a/mock-require/mock-require.d.ts b/mock-require/mock-require.d.ts new file mode 100644 index 0000000000..dded6f4224 --- /dev/null +++ b/mock-require/mock-require.d.ts @@ -0,0 +1,35 @@ +// Type definitions for mock-require v1.3.0 +// Project: https://github.com/boblauer/mock-require +// Definitions by: Daniel Pereira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** Simple, intuitive mocking of Node.js modules. */ +declare module 'mock-require' { + + interface Mock { + + /** + * @param {string} path The module you that you want to mock. + * @param {any} mockExport The function or object you want to be returned from require, instead of the path module's exports, or the module you want to be returned from require, instead of the path module's export. + */ + (path: string, mockExport: any | Function | string): void; + + /** + * @param {string} path The module you that you want to stop mocking. + */ + stop(path: string): void; + + /** This function can be used to remove all registered mocks without the need to remove them individually using mock.stop(). */ + stopAll(): void; + + /** + * @param {string} path The file whose cache you want to refresh. + */ + reRequire(path: string): void; + } + + const myModule: Mock; + export = myModule; +} \ No newline at end of file From 612e4169c6bf8b0b29d27af170d166c84f36948b Mon Sep 17 00:00:00 2001 From: Leo Liang Date: Thu, 18 Aug 2016 22:56:13 +0800 Subject: [PATCH 120/564] Change overload function order to help with resolution. --- 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 61d98fb1ee..3f47be401d 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1370,8 +1370,8 @@ declare module "dgram" { export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; interface Socket extends events.EventEmitter { - send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; send(buf: Buffer, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; bind(port?: number, address?: string, callback?: () => void): void; close(): void; address(): AddressInfo; From 903f09834da3cde4b2bd1bab80c1fd1f26597b1e Mon Sep 17 00:00:00 2001 From: Nicholas Iannone Date: Thu, 18 Aug 2016 10:31:28 -0500 Subject: [PATCH 121/564] Imported working promise library for downstream use. --- db-migrate-base/db-migrate-base.d.ts | 2 ++ db-migrate-pg/db-migrate-pg.d.ts | 1 + 2 files changed, 3 insertions(+) diff --git a/db-migrate-base/db-migrate-base.d.ts b/db-migrate-base/db-migrate-base.d.ts index fe1f4ade47..d24388fdaf 100644 --- a/db-migrate-base/db-migrate-base.d.ts +++ b/db-migrate-base/db-migrate-base.d.ts @@ -8,6 +8,8 @@ declare module "db-migrate-base" { + import * as Promise from "bluebird"; + export interface CallbackFunction { (err: any, response: any): void; } export interface InternalModule { diff --git a/db-migrate-pg/db-migrate-pg.d.ts b/db-migrate-pg/db-migrate-pg.d.ts index aa1a52d34e..533b8ff91d 100644 --- a/db-migrate-pg/db-migrate-pg.d.ts +++ b/db-migrate-pg/db-migrate-pg.d.ts @@ -10,6 +10,7 @@ declare module "db-migrate-pg" { import * as pg from "pg"; import * as DbMigrateBase from "db-migrate-base"; + import * as Promise from "bluebird"; // Yes, this is a dummy interface for now; the current implementation of the pg driver doesn't need any options. export interface CreateDatabaseOptions {} From 2104b9c513c514bc4194d72b6c3d3ece89ba0ef3 Mon Sep 17 00:00:00 2001 From: Prashant Tiwari Date: Thu, 18 Aug 2016 21:50:59 +0530 Subject: [PATCH 122/564] Distinguish between Server and Request Ext Points These are two different methods with different signatures depending on the type of the extension event. --- hapi/hapi.d.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 68f6857110..fab645ca71 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -1605,6 +1605,9 @@ declare module "hapi" { addEventListener: any; info: IServerConnectionInfo; } + + type RequestExtPoints = "onRequest" | "onPreResponse" | "onPreAuth" | "onPostAuth" | "onPreHandler" | "onPostHandler" | "onPreResponse"; + type ServerExtPoints = "onPreStart" | "onPostStart" | "onPreStop" | "onPostStop"; /** Server http://hapijs.com/api#server rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). @@ -2039,8 +2042,9 @@ declare module "hapi" { server.route({ method: 'GET', path: '/test', handler: handler }); server.start(); // All requests will get routed to '/test'*/ - ext(event: string, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; - ext(event: string, method: (request: Request, reply: IStrictReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: RequestExtPoints, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: RequestExtPoints, method: (request: Request, reply: IStrictReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: ServerExtPoints, method: (server: Server, next: (err?: any) => void, bind?: any) => void): void; /** server.handler(name, method) Registers a new handler type to be used in routes where: From 7d23177b1abff1b80b9a2d6ffbc881f6562a2359 Mon Sep 17 00:00:00 2001 From: Prashant Tiwari Date: Thu, 18 Aug 2016 22:03:03 +0530 Subject: [PATCH 123/564] Missed options in ServerExtPoints --- hapi/hapi.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index fab645ca71..ff5e1d9fe8 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -2044,7 +2044,7 @@ declare module "hapi" { // All requests will get routed to '/test'*/ ext(event: RequestExtPoints, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; ext(event: RequestExtPoints, method: (request: Request, reply: IStrictReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; - ext(event: ServerExtPoints, method: (server: Server, next: (err?: any) => void, bind?: any) => void): void; + ext(event: ServerExtPoints, method: (server: Server, next: (err?: any) => void, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; /** server.handler(name, method) Registers a new handler type to be used in routes where: From c38064c1864c5c4b92c073ada511cf23b348582b Mon Sep 17 00:00:00 2001 From: Marcel Haldemann Date: Thu, 18 Aug 2016 19:54:31 +0200 Subject: [PATCH 124/564] added support for jasmine.getEnv().defaultTimeoutInterval Its the timeout for async calls as describt here: https://github.com/mhevery/jasmine-node/blob/master/README.md --- jasmine-node/jasmine-node.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/jasmine-node/jasmine-node.d.ts b/jasmine-node/jasmine-node.d.ts index f547f844f6..f535d8c3e3 100644 --- a/jasmine-node/jasmine-node.d.ts +++ b/jasmine-node/jasmine-node.d.ts @@ -7,6 +7,12 @@ declare function it(expectation:string, assertion:(done:(err?:any) => void) => void, timeout?:number):void; +declare namespace jasmine { + interface Env { + defaultTimeoutInterval: number; + } +} + declare module "jasmine-node" { interface ExecuteSpecsOptions { specFolders: string[], From 906c5660479d5b5c36fcbfd23bae2874e80a32a5 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Thu, 18 Aug 2016 19:23:38 +0100 Subject: [PATCH 125/564] Remove commented out code Remove the code commented out. - Update the "usage" method documentation to apply to the `matches` method rather than the `regex` method. --- express-validator/express-validator.d.ts | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index 71797efce2..3599b9b79b 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -122,7 +122,6 @@ declare namespace ExpressValidator { /** * Check if length is 0 */ - //notNull(): Validator; // I don't see this in the documentation or code anywhere. isNull(): Validator; /** * Not just whitespace (input.trim().length !== 0) @@ -130,14 +129,13 @@ declare namespace ExpressValidator { notEmpty(): Validator; equals(equals:any): Validator; contains(str:string): Validator; - //notContains(str:string): Validator; // I don't see this in the documentation or code anywhere. + + /** + * Usage: matches(/[a-z]/i) or matches('[a-z]','i') + */ matches(pattern:string, modifiers?:string): Validator; matches(pattern: RegExp): Validator; - /** - * Usage: regex(/[a-z]/i) or regex('[a-z]','i') - */ - //regex(pattern:string, modifiers:string): Validator; // I don't see this in the documentation or code anywhere. - //notRegex(pattern:string, modifiers:string): Validator; // I don't see this in the documentation or code anywhere. + /** * max is optional */ @@ -200,7 +198,6 @@ declare namespace ExpressValidator { ltrim(...chars:string[]): Sanitizer; rtrim(...chars:string[]): Sanitizer; stripLow(keep_new_lines?: boolean): Sanitizer; - //ifNull(replace:any): Sanitizer; // I don't see this in the documentation or code anywhere. toFloat(): Sanitizer; toInt(radix?: number): Sanitizer; /** From 27cbba9005c03368e5d53f11465e96c560f6cdc9 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 21:52:38 +0300 Subject: [PATCH 126/564] 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 85da09fde6698a068e30da5ce464465c5c545fd5 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 21:54:51 +0300 Subject: [PATCH 127/564] Update simple-assign.d.ts --- simple-assign/simple-assign.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/simple-assign/simple-assign.d.ts b/simple-assign/simple-assign.d.ts index 1c65a8e0f9..3b9229bd65 100644 --- a/simple-assign/simple-assign.d.ts +++ b/simple-assign/simple-assign.d.ts @@ -4,6 +4,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "simple-assign" { + function simpleAssign(target: T, source: U): T & U; + 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: any, ...sources: any[]): any; export = simpleAssign; } From 227ee0d1f5c6d73e1c5ec75049ba664dab0bd6d1 Mon Sep 17 00:00:00 2001 From: Meirion Hughes Date: Thu, 18 Aug 2016 14:59:41 +0100 Subject: [PATCH 128/564] Fix SAXParser startTag attrs type. update ASTAttribute to include optional prefix field update target version improve tests --- parse5/parse5-tests.ts | 35 +++++++++++++++++++++++++++++------ parse5/parse5.d.ts | 9 +++++---- 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/parse5/parse5-tests.ts b/parse5/parse5-tests.ts index 420fda5992..090217a6e2 100644 --- a/parse5/parse5-tests.ts +++ b/parse5/parse5-tests.ts @@ -1,6 +1,6 @@ // Type definitions for parse5 2.1.5 // Project: https://github.com/inikulin/parse5 -// Definitions by: Nico Jansen +// Definitions by: Nico Jansen , Meirion Hughes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -9,33 +9,56 @@ import * as parse5 from 'parse5'; // parse5.SAXParser() var parser = new parse5.SAXParser({ locationInfo: true }); + +var _wasCalled = false; + parser.on('startTag', (name, attrs, selfClosing, location) => { console.log(name, attrs, selfClosing, location); + console.log(attrs[0].name); + console.log(attrs[0].prefix); + console.log(attrs[0].value); + + if(name == "use") + if(attrs[0].prefix === undefined) + throw "prefix wasn't defined on known attr" + + _wasCalled = true; }); + parser.on('text', (text, location) => { console.log(text, location); }); +parser.write('some text'); +parser.write(''); + +if(!_wasCalled) + throw "parser.on 'startTag' wasn't called"; + // parse5.parse() -parse5.parse('html', { locationInfo: true, treeAdapter: parse5.treeAdapters.default }); +parse5.parse('', { locationInfo: true, treeAdapter: parse5.treeAdapters.default }); parse5.parse('html', {}); -parse5.parse('html'); +parse5.parse(''); // parse5.ParserStream() var parserStream = new parse5.ParserStream({ locationInfo: true, treeAdapter: parse5.treeAdapters.htmlparser2 }); parserStream = new parse5.ParserStream({ }); parserStream = new parse5.ParserStream(); + +parserStream.write(""); + var node = parserStream.document.childNodes[0]; + node.parentNode.attrs = [{name: '', value: ''}]; // parse5.parseFragment() -var fragment = parse5.parseFragment(''); -fragment = parse5.parseFragment('', {locationInfo: true}); +var fragment = parse5.parseFragment('
    '); +fragment = parse5.parseFragment('
    ', {locationInfo: true}); // parse5.ASTNode fragment.quirksMode = true; fragment.namespaceURI = ''; fragment.nodeName = ''; fragment.value = ''; -fragment = fragment.parentNode; fragment = fragment.childNodes[0]; +fragment = fragment.parentNode; diff --git a/parse5/parse5.d.ts b/parse5/parse5.d.ts index 69bfd1419e..bb77d6c0c3 100644 --- a/parse5/parse5.d.ts +++ b/parse5/parse5.d.ts @@ -1,6 +1,6 @@ -// Type definitions for parse5 2.1.5 +// Type definitions for parse5 2.2.0 // Project: https://github.com/inikulin/parse5 -// Definitions by: Nico Jansen +// Definitions by: Nico Jansen , Meirion Hughes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -45,6 +45,7 @@ declare module 'parse5' { export interface ASTAttribute { name: string; value: string; + prefix?: string; } export interface Attribute { @@ -126,10 +127,10 @@ declare module 'parse5' { /** * Raised when the parser encounters a start tag. * Listener function has 4 parameters: - * Tag name, List of attributes in the { key: String, value: String } form, selfClosing boolean + * Tag name, List of attributes in the { name: String, value: String, prefix?: String } form, selfClosing boolean * and start tag source code location info. Available if location info is enabled in SAXParserOptions. */ - on(event: 'startTag', listener: (name: string, attrs: Attribute[], selfClosing: boolean, location?: StartTagLocationInfo) => void): this; + on(event: 'startTag', listener: (name: string, attrs: ASTAttribute[], selfClosing: boolean, location?: StartTagLocationInfo) => void): this; /** * Raised when parser encounters an end tag. * Listener function has 2 parameters: From d3d99d650b27beaf7f8c436f3e49f96977a5aec9 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Thu, 18 Aug 2016 22:35:52 +0300 Subject: [PATCH 129/564] 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 130/564] 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 b110a22d2660d42dc4708c1a0f44828f6737d554 Mon Sep 17 00:00:00 2001 From: Meirion Hughes Date: Thu, 18 Aug 2016 21:03:32 +0100 Subject: [PATCH 131/564] Fix target version in test file --- parse5/parse5-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parse5/parse5-tests.ts b/parse5/parse5-tests.ts index 090217a6e2..05e1ea683e 100644 --- a/parse5/parse5-tests.ts +++ b/parse5/parse5-tests.ts @@ -1,4 +1,4 @@ -// Type definitions for parse5 2.1.5 +// Type definitions for parse5 2.2.0 // Project: https://github.com/inikulin/parse5 // Definitions by: Nico Jansen , Meirion Hughes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 07b2e6b616344176a6bc8da71edd2f54c0b9e090 Mon Sep 17 00:00:00 2001 From: Paul van Brenk Date: Thu, 18 Aug 2016 13:07:30 -0700 Subject: [PATCH 132/564] Remove duplicate method and re-order some --- multer/multer.d.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/multer/multer.d.ts b/multer/multer.d.ts index 2ffaf61760..d9abb4a87c 100644 --- a/multer/multer.d.ts +++ b/multer/multer.d.ts @@ -87,18 +87,16 @@ declare module "multer" { } interface Instance { + /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ + single(): express.RequestHandler; /** Accept a single file with the name fieldname. The single file will be stored in req.file. */ single(fieldame: string): express.RequestHandler; /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ - single(): express.RequestHandler; + array(): express.RequestHandler; /** Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files. */ array(fieldame: string, maxCount?: number): express.RequestHandler; - /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ - array(): express.RequestHandler; /** Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files. */ fields(fields: Field[]): express.RequestHandler; - /** Accepts all files that comes over the wire. An array of files will be stored in req.files. */ - any(): express.RequestHandler; /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ any(): express.RequestHandler; } From d71b7c3821e24a0c167722e675445c6a6b6a9237 Mon Sep 17 00:00:00 2001 From: Chris Manning Date: Fri, 19 Aug 2016 15:13:47 +1200 Subject: [PATCH 133/564] 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 134/564] 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 135/564] 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 136/564] 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 137/564] 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 138/564] 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 139/564] 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 140/564] 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 141/564] 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 142/564] 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 143/564] 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 144/564] 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 145/564] 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 146/564] 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 147/564] 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 148/564] 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 149/564] 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 150/564] 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 151/564] 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 152/564] 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 88c5e9aca6c4a8c065cca68204ba36b8c2ffdb73 Mon Sep 17 00:00:00 2001 From: Maciej Suchecki Date: Sat, 20 Aug 2016 11:54:27 +0200 Subject: [PATCH 153/564] 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 154/564] 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 155/564] 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 156/564] 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 157/564] 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 158/564] 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 159/564] 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 dc124b25ba5bdffd722576a6eaa6595deb8a35e6 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 7 Aug 2016 23:38:46 -0400 Subject: [PATCH 160/564] 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 161/564] 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 162/564] 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 163/564] 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 164/564] 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 165/564] 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 166/564] 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 167/564] 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 168/564] 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 169/564] 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 170/564] 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 171/564] 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 172/564] 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 173/564] 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 174/564] 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 175/564] 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 176/564] 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 177/564] 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 3636b4436eb3f76101c1991ed1a83d855aeca0ec Mon Sep 17 00:00:00 2001 From: hanjung Date: Mon, 22 Aug 2016 20:53:57 -0700 Subject: [PATCH 178/564] 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 fe5c10be966bf1949ccd2811b430b0e666ff7829 Mon Sep 17 00:00:00 2001 From: Gabriel JUCHAULT Date: Tue, 23 Aug 2016 13:27:40 +0200 Subject: [PATCH 179/564] 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 180/564] 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 181/564] 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 182/564] 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 183/564] 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 184/564] 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 185/564] 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 186/564] 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 187/564] 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 188/564] 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 189/564] 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 190/564] 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 191/564] 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 192/564] 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 193/564] 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 194/564] 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 195/564] 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 196/564] 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 197/564] 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 198/564] 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 199/564] 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 200/564] 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 201/564] 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 2d3fcf5b626d5c0b89d1b93b5f2dd802f2036f44 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Thu, 25 Aug 2016 22:49:18 +0900 Subject: [PATCH 202/564] 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 203/564] 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 204/564] 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 205/564] 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 206/564] 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 207/564] 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 208/564] 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 209/564] 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 210/564] 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 211/564] 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 212/564] 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 213/564] 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 214/564] 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 215/564] 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 216/564] 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 c3d42974315ac7f01a56ce10b57e7b71affbe8e9 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Sat, 27 Aug 2016 00:43:42 +0800 Subject: [PATCH 217/564] 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 218/564] 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 219/564] [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 493/564] 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 494/564] 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 495/564] [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 496/564] =?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 497/564] 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 498/564] 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 499/564] 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 500/564] [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 501/564] 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 502/564] 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 503/564] [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 504/564] 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 505/564] 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 506/564] 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 f105740dced564894ee5a12c36fce6a82af9a849 Mon Sep 17 00:00:00 2001 From: Ben Mosher Date: Mon, 12 Sep 2016 08:45:01 -0400 Subject: [PATCH 507/564] 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 508/564] [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 509/564] [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 874a60bc6803c2ce7eb1103be41be5a203e5a323 Mon Sep 17 00:00:00 2001 From: Marcin Kral Date: Wed, 14 Sep 2016 13:39:53 +0200 Subject: [PATCH 510/564] 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 511/564] 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 512/564] 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 513/564] 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 514/564] 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 515/564] 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 516/564] 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 517/564] 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 518/564] 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 519/564] 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 520/564] 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 521/564] 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 522/564] 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 523/564] [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 524/564] [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 525/564] 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 526/564] [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 527/564] 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 528/564] 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 529/564] 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 530/564] 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 531/564] 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 532/564] 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 533/564] 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 534/564] 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 535/564] 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 536/564] 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 537/564] 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 538/564] 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 539/564] 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 540/564] [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 541/564] 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 542/564] [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 543/564] 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 544/564] 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 545/564] 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 546/564] 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 547/564] 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 47588ba8f9a2ceb05acef2ec2c69263cf057405d Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Wed, 14 Sep 2016 11:27:33 -0700 Subject: [PATCH 548/564] [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 36d40a63a05b5cb3413737fbdf7c9a2a26f211fd Mon Sep 17 00:00:00 2001 From: Craig Date: Wed, 14 Sep 2016 16:56:35 -0700 Subject: [PATCH 549/564] 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 550/564] 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 551/564] 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 552/564] 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 553/564] 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 554/564] 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 555/564] 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 556/564] [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 557/564] [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 558/564] [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 559/564] 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 560/564] [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 561/564] [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 562/564] 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 563/564] 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 7c9f3114a756f052ca10caba615540d7b5eb19be Mon Sep 17 00:00:00 2001 From: Dave Dunkin Date: Fri, 16 Sep 2016 12:10:31 -0700 Subject: [PATCH 564/564] 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;